Hey there,
This might just be a lack of me understanding so I apologize in advance if so, but i seem to be having some trouble understanding the state sync.
Also know the code is just thrown together for learning purposes and to see if i can get something working.
My Server Code:
export class Player {
id: string;
position: {
x: number,
y: number,
z: number
} = {
x: 0,
y: 0,
z: 0
};
updatePosition(key) {
switch(key) {
case 'A':
this.position.x -= 0.1;
case 'S':
this.position.z -= 0.1;
case 'D':
this.position.x += 0.1;
case 'W':
this.position.z += 0.1;
default:
break;
}
}
}
Then in the main Room code after a player has joined, i listen for a input message and call the above code with this:
onMessage (client, data) {
console.log(client.id, "sent", data)
if (data.action) {
if (data.action === 'Input') {
this.handleMovement(client.sessionId, data.key)
}
}
}
handleMovement (id, key) {
this.state.players[id].updatePosition(key);
}
In my unity client side i have this code.
IEnumerator Start () {
...
room.Listen ("players/:id/:position/:attribute", this.OnPlayerChange);
...
}
void HandlePlayerInput()
{
if (Input.GetKeyDown("a"))
{
room.Send(new { action = "Input", key = "A"});
}
if (Input.GetKeyDown("s"))
{
room.Send(new { action = "Input", key = "S"});
}
if (Input.GetKeyDown("d"))
{
room.Send(new { action = "Input", key = "D"});
}
if (Input.GetKeyDown("w"))
{
room.Send(new { action = "Input", key = "W"});
}
}
void OnPlayerChange(DataChange change)
{
GameObject curPlayer;
players.TryGetValue(change.path["id"], out curPlayer);
if (curPlayer)
{
switch (change.path["attribute"])
{
case "x":
curPlayer.transform.position = new Vector3(float.Parse(change.value.ToString()), curPlayer.transform.position.y, curPlayer.transform.position.z);
break;
case "y":
curPlayer.transform.position = new Vector3(curPlayer.transform.position.x, float.Parse(change.value.ToString()), curPlayer.transform.position.z);
break;
case "z":
curPlayer.transform.position = new Vector3(curPlayer.transform.position.x, curPlayer.transform.position.y, float.Parse(change.value.ToString()));
break;
default:
break;
}
}
}
All of this works Kinda great. I see the box spawn, i can kinda move it around, but the movement isn't perfect.
When i hit the "a" key nothing happens. I logged once on the server and it is setting my players x position to -0.1, but the message never seems to come to unity.
When i hit "w" all works as expected. (box moves up the z plane, camera is directly above box so x,z planes are the movements.)
When i hit "d" the box moves both up the x plane and the z plane in a diagonal direction?
And finally when i hit the "s" button nothing happens.
Any ideas as to what i might be doing wrong?
Thanks,
Cody