Skip to content

Instantly share code, notes, and snippets.

@thc282
Last active June 25, 2024 09:26
Show Gist options
  • Save thc282/301db515590d5bbdc1b8c8be43e24c81 to your computer and use it in GitHub Desktop.
Save thc282/301db515590d5bbdc1b8c8be43e24c81 to your computer and use it in GitHub Desktop.
the code to calculate the interpolation

1. First calculate the speed

speed = (currentTime - startTime) / (endTime - startTime)

frame = Date.now()
const speed = (frame - positions[0].frame) / (positions[0 + delay].frame - positions[1 + delay].frame);
  • The interpolation factor speed represents the position between the two most recent positions in the positions array.
  • frame is the current frame of the game.
  • positions[0].frame is the frame of the most recent position in the positions array.
  • positions[0 + delay].frame and positions[1 + delay].frame are the frames of the two most recent positions, with a delay offset.
  • The formula (frame - positions[0].frame) / (positions[0 + delay].frame - positions[1 + delay].frame) calculates the interpolation factor speed as a value between 0 and 1, based on the current frame and the frames of the two most recent positions.

2. Second calculate the interpolate point

interpolate point = (1 - speed) * from + speed * to

clientPlayerInterpolated.pos.x = (1 - speed) * positions[1 + delay].x + speed * positions[0 + delay].x;
clientPlayerInterpolated.pos.y = (1 - speed) * positions[1 + delay].y + speed * positions[0 + delay].y;
  • The formula (1 - speed) * positions[1 + delay].x + speed * positions[0 + delay].x performs the linear interpolation between the x-coordinates of the two most recent positions.
  • The formula (1 - speed) * positions[1 + delay].y + speed * positions[0 + delay].y performs the linear interpolation between the y-coordinates of the two most recent positions.

details code

const speed = (frame - positions[0].frame) / (positions[0 + delay].frame - positions[1 + delay].frame);
clientPlayerInterpolated.pos.x = (1 - speed) * positions[1 + delay].x + speed * positions[0 + delay].x;
clientPlayerInterpolated.pos.y = (1 - speed) * positions[1 + delay].y + speed * positions[0 + delay].y;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment