I’m using LineRenderers for this snake-like object (looking at it from topdown perspective), where the head of the snake is the first point of the line following its transform as it moves around, and the rest of the points are supposed to follow it on a delay. This code I have below works, but it’s not framerate independent and I just can’t figure out how to fix that – I’m already using deltaTime. At lower framerates, the points can’t keep up as well and it starts to stretch out. Any idea what’s going on here?
LineRenderer line; // The line
int lineCount = 35; // The number of points in the line
Vector2[] positions = new Vector2[35]; // An array holding the points of the line, since I can't access them directly
float speed = 300; // Speed the head of the snake is moving
float lerpSpeed = 15; // Speed the rest of the points lerp to catch up
void Update() {
// Move snake's head and set the first line point to it
_transform.Translate(new Vector3(speed*Time.deltaTime, 0, 0), Space.Self);
positions[0] = _transform.position;
line.SetPosition(0, _transform.position);
// Iterate through positions and lerp each one towards the next one to follow it
// backwards or forwards, neither way works: for (int i=positions.Length-1; i>0; i--) {
for (int i=1; i<positions.Length; i++) {
positions[i] = Vector2.Lerp(positions[i], positions[i-1], lerpSpeed*Time.deltaTime);
}
// Set line points
for (int i=1; i<lineCount; i++) {
line.SetPosition(i, new Vector3(positions[i].x, positions[i].y, 0));
}
}