Ashish Ashish - 1 month ago 14
Javascript Question

How can I update my sprite position according input coordinates coming through Web Socket

I am new to phaser framework. I am working on a game where I am getting a coordinates for sprites through web Socket. The problem is how can I update my sprite according to incoming coordinates?

/************ON RECEIVING MESSAGES VIA WEBSOCKET FROM THE SERVER********/
ws.onmessage = function(event) {
var mySpan = document.getElementById("messageGoesHere");
var mySpan2 = document.getElementById("messageGoesHere2");
var str = event.data;
if((str.localeCompare('connected'))==0) {
document.getElementById("connection").innerHTML='Connected';
}
else if((str.localeCompare('closed'))==0) {
document.getElementById("connection").innerHTML='No connection';
}
else {
var array = str.split('|');
mySpan.innerHTML = parseInt(array[2])
mySpan2.innerHTML = parseInt(array[3]);
draw(parseInt(array[2]), parseInt(array[3]));

var x = parseInt(array[2]);
console.log(x);

var y = parseInt(array[3]);
console.log(y);
}

Answer

If you use the maxTime argument you will know when your object will reach its destination and you can use a timer to stop the object at that exact same time, for example:

Move towards target in 2 seconds

game.physics.arcade.moveToXY(player,320,240,0,2000);

Stop movement after 2 seconds (should be on target)

game.time.events.add(2000, function () {
   player.body.velocity.x = 0;
   player.body.velocity.y = 0;
}, this);

Keep in mind that maxTime is not 100% accurate due to how browser timers work, so it could differ a few milliseconds.