在上一篇文章中,我們以客戶端的角度去寫了玩家移動的Script,那這篇文章就從上篇文章接續下去。
在伺服器端,我們在之前建立的 Server 腳本中在玩家連線後把它們先初始化;我們需要一個ServerHandle來處理收到封包後,後續要執行的動作指令,我們還需要一個Player腳本來處理所有角色的移動。
private static void InitializeServerData()
{
for (int i = 1; i <= MaxPlayers; i++)
{
clients.Add(i, new Client(i));
}
packetHandlers = new Dictionary<int, PacketHandler>()
{
{ (int)ClientPackets.welcomeReceived, ServerHandle.WelcomeReceived },
{ (int)ClientPackets.playerMovement, ServerHandle.PlayerMovement },
};
Console.WriteLine("Initialized packets.");
}
public static void PlayerMovement(int _fromClient, Packet _packet)
{
bool[] _inputs = new bool[_packet.ReadInt()];
for(int i = 0; i < _inputs.Length; i++)
{
_inputs[i] = _packet.ReadBool();
}
Quaternion _rotation = _packet.ReadQuaternion();
Server.clients[_fromClient].player.SetInput(_inputs, _rotation);
}
public void Update()
{
Vector2 _inputDirection = Vector2.Zero;
if (inputs[0])
{
_inputDirection.Y += 1;
}
if (inputs[1])
{
_inputDirection.Y -= 1;
}
if (inputs[2])
{
_inputDirection.X += 1;
}
if (inputs[3])
{
_inputDirection.X -= 1;
} Move(_inputDirection);
}
private void Move(Vector2 _inputDirection)
{
Vector3 _forward = Vector3.Transform(new Vector3(0, 0, 1), rotation);
Vector3 _right = Vector3.Normalize(Vector3.Cross(_forward, new Vector3(0, 1, 0)));
Vector3 _moveDirection = _right * _inputDirection.X + _forward * _inputDirection.Y;
position += _moveDirection * moveSpeed;
ServerSend.PlayerPosition(this); ServerSend.PlayerRotation(this);
}
public void SetInput(bool[] _inputs, Quaternion _rotation)
{
inputs = _inputs; rotation = _rotation;
}