Brandon Reed
Brandon Reed

Reputation: 5

Libgdx - Slowing Projectile to stop, then Reversing it

When working with creating games in Libgdx, I have not been using the physics engine as I dont have too many moving parts in the game. So, to have objects fall from the top of the screen to the bottom, I used what the documentation had, something like this:

projectile.y -= 200 * Gdx.graphics.getDeltaTime();

That example will make said projectile go down at 200 pixels per second (I believe). What I am trying to do is make it so after two seconds, the projectile will transition from negative 200 per second, to positive 200 per second. I've tried using loops and Thread.sleep, but that will just freeze the entire game and unfreeze with the projectiles going the other way. Any ideas?

Upvotes: 0

Views: 267

Answers (3)

Juraj Pancik
Juraj Pancik

Reputation: 301

If you are looking for linear interpolation of the speeds, just keep track of time.

float timeElapsed = 0.0f;

void render() {
    timeElapsed += Gdx.graphics.getDeltaTime();

    projectile.y -= 200.0f * (1.0f - timeElapsed);
}

Be sure to stop after timeElapsed has reached 2 seconds (that's if(timeElapsed < 2.0f)). Time elapsed variable will start at 0.0f and will slowly increment. Until it reaches 1.0f, projectile.y will get substracted from. However, as soon as time elapsed is higher than 1.0f, projectile.y will get added to.

Upvotes: 0

user447688
user447688

Reputation:

To get a change in direction of y, you need a polynomial function of x. For a single direction change, use a binomial; try something like

projectile.y = projectile.y 
    - 200 * Gdx.graphics.getDeltaTime() 
    + 20 * Math.pow(Gdx.graphics.getDeltaTime(), 2);

Upvotes: 0

EpicPandaForce
EpicPandaForce

Reputation: 81549

Linear interpolation.

All you need to do is determine the start point: x1 = -200

Determine the end point: x2 = 200

Determine the amount of seconds that it takes to reach the end point: tmax = 2.0 sec

Determine the difference that you need to add to the original to reach the end point: v = (x2-x1) = (200 - (-200)) = 400

Use the linear interpolation function: x1 + t*v = x2 where t e [0...1] //must be normalized to 0..1 interval

Thus at t = 0, the value is at x1 + 0 = x1; and at t = (tn/tmax) [which is 1], the value is at x1 + v = x2.

So all you need is a timer from 0 to 2 and the following equation:

float interpolationTimer = 0.0f;
final float interpolationTimerMax = 2.0f;

public void render()
{
    float delta = Gdx.graphics.getDeltaTime();
    interpolationTimer += delta;
    if(interpolationTimer > interpolationTimerMax )
    {
        interpolationTimer = interpolationTimerMax ;
    }
    velocity.y = -200 + (interpolationTimer/interpolationTimerMax) * (400); //x1 + t*v = x2
    projectile.y -= velocity.y * delta;
}

Upvotes: 1

Related Questions