3
\$\begingroup\$

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){

    velocity.add(acceleration.cpy().scl(delta));
    position.add(velocity.cpy().scl(delta));
    displacement.add(velocity.cpy().scl(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!

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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? \$\endgroup\$ Commented May 22, 2015 at 10:56
  • \$\begingroup\$ Not at all, just hit that checkmark and give me a vote up if you think I deserve it. \$\endgroup\$
    – JPtheK9
    Commented May 22, 2015 at 16:22
  • 1
    \$\begingroup\$ Ok. Thank you. As soon as I have enough reputation I will give you a vote up! \$\endgroup\$ Commented May 23, 2015 at 19:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .