# Fixed distance smooth snake movement

This topic is 506 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Snake movement probably has been asked and answered many times before. I managed to do some basic snake movement. But I find it hard to fix the distance. Let me explain my problem.

The code I am using is like this:

const dx = this.tracer.x - this.x;
const dy = this.tracer.y - this.y;

const actualDistance = Math.hypot(dx, dy);

this.vx = this.tracer.speed * ( dx / actualDistance ) || 0;
this.vy = this.tracer.speed * ( dy / actualDistance ) || 0;

if (actualDistance >= this.distance) {
this.x += this.vx;
this.y += this.vy;
} else {
this.x += lerp(0, this.vx, actualDistance / this.distance);
this.y += lerp(0, this.vy, actualDistance / this.distance);
}

The above code is in the "update" function of each snake segment. Each segment will follow the previous segment to its target position. The tracer means the body which is following by current body. The distance is a pre-calculated fixed value.

I want to move the snake at normal speed, or at a higher speed, or slow down to normal speed. Like that in slither.io.

This is not hard to do using my script. I can move my snake at normal speed or speed up or slow down with all the bodies following the previous one. I can also turn or rotate the snake smoothly.

But there is one problem when I try to move fast and rotate at the same time. The snake will squeeze shorter which means all the distance between two adjacent bodies become shorter. So the snake looks like a smaller one when it is doing a fast turn. This will last until it slows down its speed to normal and it's back to its normal shape.

All I want is make it same size as normal no matter how I turn or rotate the snake at any speed. Can this be achieved?

Edited by caymanbruce

##### Share on other sites
On 07/07/2017 at 6:26 PM, caymanbruce said:

when I try to move fast and rotate at the same time. The snake will squeeze shorter

That's some relativity effect right there.

But seriously, if you are doing everything right, then my guess is that you aren't restricting change of angle which just makes the snake contract because the actualDistance doesn't exceed your desired fixed distance and fall into heavy lerp-ing.

While playing slither.io, then you might have noticed that the rate of change in angle is (or at least looks like it is) proportional to time difference, so when traveling faster the change of angle is even smaller per unit distance traveled.

1. 1
2. 2
Rutin
21
3. 3
4. 4
A4L
15
5. 5
khawk
14

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633737
• Total Posts
3013608
×