# Endless Running Game - Changing Lane Function in JAVA

I am developing a kind of vertical endless running game, where the character has 4 possible lanes to be in. I am using libGDX and want the character to change lanes by adding a horizontal velocity to a Vector2. The position will be upgraded by velocity increments and not by simply changing the position to the next lane. So far I have a working function, but as I increment the horizontal velocity, along the run, it loses accuracy. Let's assume each lane is 50px width.

I am also using a acceleration vector to slow down as the character gets closer to the next lane.

The 2 functions below are about what happens when the screen is touched right or left. The position verification is a boundary condition to avoid the character going off the screen.

public void onClickRight(){
if(!(position.x>=50*2.75)&&isAlive){
velocity.x=350+extraSlideSpeed;
acceleration.x=-500;
}

}

public void onClickLeft(){
if(!(position.x<=50*0.75)&&isAlive){
velocity.x=-350-extraSlideSpeed;
acceleration.x=500;
}
}


The function below is called about 60 times per second, as delta is a very small number and represents time.

public void updateRunning(float delta){

if(displacement.x>=50||displacement.x<=-50){
velocity.x = 0;
acceleration.x = 0;
displacement.x = 0;
}
}


I am looking for smarter options as I am not pleased with my own. Help would be appreciated!

You should do a bounds check as you mentioned then reduce the velocity so you don't get shaky behavior. You kind of got it but I'm not sure what displacement does.

//This code goes after velocity is set
if (position.x > 50)
{
position.x = 50;
//If we're heading towards the bounds, stop
if (velocity.x > 0) velocity.x = 0;
}
else if (position.x < -50)
{
position.x = -50;
if (velocity.x < 0) velocity.x = 0;
}


Velocity can be handled however you like but the above code should ensure that the runner stays between -50 and 50 inclusive and doesn't shake when it hits a bound.

• Perfect! This is exactly what I was missing, a line to set the position to the correct point after my conditions are satisfied. So simple and I could not figure out myself! Thank you so much. Do I have to do any edits to the question/answer? – Herbert Souza Silva May 22 '15 at 10:56
• Not at all, just hit that checkmark and give me a vote up if you think I deserve it. – JPtheK9 May 22 '15 at 16:22
• Ok. Thank you. As soon as I have enough reputation I will give you a vote up! – Herbert Souza Silva May 23 '15 at 19:55