Player moving on a grid line

How can I make my player move on a grid line?

I have my code here to make the player move up:
this.snakePos.y += this.moveSpeed * deltaTime which I want to make my player move with the integer number. I try to use Math.round(this.snakePos.y += this.moveSpeed * deltaTime) but it resulted nothing

Need more details about what your snakePos is and how it’s suppose to be synced with the position

I declare snakePos as a new Vec3, then I update the node.position based on its value.
For example:
if (this.up == 1) {
this.snakePos.y += this.moveSpeed * deltaTime;
console.log(this.snakePos.y);
this.snake.setPosition(this.snakePos);
}

What your log gives you

I use console.log to see if the value is rounded or not
the log is “-35.43011964421286” for the x position when moving left

deltaTime is not a fixed value, you can only get a non-fixed value by multiplying speed by it. You can use an approximation value: Math.floor(1 /game.frameRate * 1000)/ 1000

I tried using:

Math.floor(this.moveSpeed * deltaTime)

to round the number but it makes no difference to my code above

It should be very straight forward though, maybe your speed is too small and doesn’t show enough movement, the delta time is in seconds, for a normal frame in 60fps, the value of deltaTime would be around 0.016s

have you tried this if i’m not misunderstanding?

this.snakePos.y = Math.round(this.snakePos.y + this.moveSpeed * deltaTime)

I set moveSpeed to 200 and its kinda fast

I tried and it moves like the Flash :joy:

Okay so I think of another solution. I will divine the canvas into a grid system and will move my character based on these grid cells. Will this work?

As long as the position set is taking effect, then it’s not a technical issue. It’s more about gameplay and all depends on what you want.

1 Like