Setting up the game-server by C# socket
Input from the client and server returns the position
We're trying to set up the socket-server instead of using "Photon Engine", which the flexibility is much higher. In this week, I am trying to let the player sending input from the client-side and let the server to return the position of the player. This design could prevent player cheats through the client-side.
Client-side
PlayerController - a class which detect player's input and sending them to serverpublic class PlayerController : MonoBehaviour
{
private void FixedUpdate()
{
SendInputToServer();
}
private void SendInputToServer()
{
bool[] _inputs = new bool[]
{
Input.GetKey(KeyCode.W),
Input.GetKey(KeyCode.A),
Input.GetKey(KeyCode.S),
Input.GetKey(KeyCode.D)
};
ClientSend.PlayerMovement(_inputs);
}
}
public static void PlayerPosition(Packet _packet)
{
int _id = _packet.ReadInt();
Vector3 _position = _packet.ReadVector3();
MainGame.players[_id].transform.position = _position;
}
public static void PlayerRotation(Packet _packet)
{
int _id = _packet.ReadInt();
Quaternion _rotation = _packet.ReadQuaternion();
MainGame.players[_id].transform.rotation = _rotation;
}
Server-side
ServerHandle.PlayerMovement - a function that receives the input from the client
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);
}
Player class - a class handles the input sent from the client and return the latest position back to client
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);
}


Comments
Post a Comment