# Implement an “xprevious” in LibGDX

I have used Gamemaker Studio 2 before, briefly, and found that the xprevious and yprevious variables are extremely useful.

Since I am developing a pixel-based roguelike in LibGDX, what is the best way to implement this? I was using this logic:

1. Create two variables, x, xprev
2. In the render loop (or in the player class) make xprev equal to x
3. change x by player speed
4. Repeat 2 & 3

However, this seems to be very glitchy. Here is my render function:

player.xprevious = player.position.x;
player.yprevious = player.position.y;

if(movingRight) player.position.x += speed
if(movingLeft) player.position.x -= speed;
if(movingUp) player.position.y += speed;
if(movingDown) player.position.y -= speed;


Since after this code the position is not being changed until the next iteration, player.position.x and player.xprevious should be different?

Right after this, I logged the values of the variables, e.g.:

xprev 716.0, x 716.0 yprev 1435.0, y 1435.0

Help is greatly appreciated! Thanks.

• Can you describe the precise glitches you're observing? And show us the particular order in which you do these actions in your game loop? – DMGregory Apr 10 at 2:20
• I added some code to elaborate. Hope this helps. – Rohan Apr 10 at 2:24
• If I may ask, why are you setting xprevious = x? I cannot expect them to be different because you're making them equall. But the code automatically sets xprevious to the 'previous x' since the last frame. If the position hasn't changed, then the previous x will stay equall to the current x. – Steven Apr 10 at 6:24
• Looking at the code as it is, there must be something either changing xprevious, or position.x isn't being changed. – Steve Smith Apr 11 at 11:17