I'm writing a tank trouble clone just for fun using phaser and node, so this is my tank instantiation
tank = game.add.sprite(Math.random() * 800, Math.random() * 640, 'tank');
tank.anchor.setTo(0.5, 0.5);
tank.scale.setTo(0.5, 0.5);
game.physics.arcade.enable(tank);
tank.body.immovable = true;
tank.body.collideWorldBounds = true;
This is how an enemy tank is defined at the client
var Enemy = function (game, id, x, y, angle) {
this.id = id;
this.x = x;
this.y = y;
this.angle = angle;
// set the tank properties
this.tankEnemy = game.add.sprite(this.x, this.y, 'enemy');
this.tankEnemy.anchor.setTo(0.5, 0.5);
this.tankEnemy.scale.setTo(0.5, 0.5);
// game.physics.arcade.enable(this.tankEnemy)
// this.tankEnemy.body.immovable = true;
// this.tankEnemy.body.collideWorldBounds = true;
}
The problem is in the above case I have enemy tank at the client as a non body (which means I'm checking the collision between a "body" and a "non body") and when I try to check collision
game.physics.arcade.collide(tank, enemies[i].tankEnemy);
It doesn't work.
So I tried making it a body by un-commenting the code, now the enemy tank behaves more weirdly than before. Whenever a client moves, it gains velocity for other clients, making it go beyond the map and becoming invisible. Whereas I'm just changing the coordinates for other clients -
function tankUpdate (data) {
// when the update event is fired
var moveTank = findTank(data.id);
if (!moveTank) {
console.log('tank not found');
return;
}
// update the tank location
moveTank.tankEnemy.x = data.x;
moveTank.tankEnemy.y = data.y;
moveTank.tankEnemy.angle = data.angle;
}
This is how a client emits update event -
socket.emit('update location', {x: tank.x, y: tank.y, angle: tank.angle});
The server in turn broadcasts this update, which leads to the calling of tankUpdate
.
What is the right way to implement this? I just want to prevent the collision between tanks.
EDIT
After a long discussion with @Hexus on slack we concluded with these points which solved the issue -
I was not sending the velocity to the server. (@Hexus mentioned it in his answer).
I was setting the
sprite.x
property which was conflicting with the position ofbody
.sprite.body.x
is the right property to set.I was updating the position and velocity as soon as I received from the server which leads to a shaky and not-so-smooth movement. The idea is to create a buffer and then update.
Lastly but the most important, if you are testing the game without two instances running on the same machine/browser make sure you set
game.stage.disableVisibilityChange = true;
in yourcreate
method.
Again thanks a lot to @Hexus for helping!