I'm creating a small game to learn how NodeJS & Sails work (and by extension Waterline, Socket.io, Express, and all their components).
I'm using websockets to make the server calculate the coordinates. Everything is handled server-side.
The client only receives serialized data in order to redraw the whole canvas.
For debugging purposes, I decided not to redraw but simply "draw" (leaving the old canvas visible) to show you the result.
See below for situation, issue and code.
The issue
I'm having trouble when calculating coordinates.
What I need is a simple forward/backwards system, and when pressing left
or right
keys, change the direction angle so the character can move in the canvas.
Kinda like the good'ol Asteroids retro games.
The issue is the following:
The drawn loops you see shouldn't exist. In fact, they should be circles. I drew this by simply pressing either up
or down
key, combined with one of left
or right
keys.
I think there is an issue in the calculation system...
This shouldn't be a performance issue because each tick occurs at the same interval, so even if it was a performance issue, it should only be related to delay when redrawing the canvas, not such an offset in coordinates calculation...
Any idea ?
Info about code api
moves
contains a javascript object like this:
{ left:false, right: false, up: false, down: false }
It is used to check whether the user is "pressing" associated arrow keys.
It is updated each time there is akeyUp
orkeyDown
event client-side.user.pick
contains the "physical object" to be rendered in the canvas, which containx
,y
coordinates, and information about movement speed and rotation speed.
Here's the code that handles the coordinates calculation.
// Change angle if "left" or "right" is pushed
if (moves.left || moves.right) {
// let PI2 = 2 * PI;
let angle = user.pick.angle;
if (moves.left) {
angle += user.pick.angleSpeed;
} else if (moves.right) {
angle -= user.pick.angleSpeed;
}
// Use this to avoid having huge integers to manage
if (angle < 0) {
angle = 360 - angle;
}
if (angle > 360) {
angle = angle - 360;
}
user.pick.angle = parseInt(angle);
}
// Up and down allow us to move either forwards or backwards.
if (moves.up || moves.down) {
let moveRatio = moves.up ? 1 : -1;
let angleRadians = user.pick.angle * (PI / 180);
let x = user.pick.x + moveRatio * user.pick.speed * Math.sin(angleRadians);
let y = user.pick.y + moveRatio * user.pick.speed * Math.cos(angleRadians);
// Avoids collisions with canvas walls
if (x > 0 && x < user.map.width) {
user.pick.x = parseInt(x);
}
if (y > 0 && y < user.map.height) {
user.pick.y = parseInt(y);
}
}
angle + 360
not360 - angle
. For example, let angle be -30. Our expected output is +330. This code gives us 360 - (-30) = 390, then the nextif
triggers and we get 390 - 360 = 30, so our angle has been inverted. I don't think this is the whole cause of the error you observe, but it's low-hanging fruit to fix. \$\endgroup\$