Getting the sinking feeling

I am implementing basic gravity+floor collision but due to the speed always increasing, after I hit the floor I sink like im stood in quicksand, the issue is that if I put an 'if !grounded around the gravity calculations jumping will not work.

Any ideas?

private void gravity() {

	float Y = sprite.getY();

	speed += accel * Gdx.graphics.getDeltaTime();
	Y += speed * Gdx.graphics.getDeltaTime();
	sprite.setY(Y);

	if (sprite.getY() <= floor) {
		grounded = true;
		speed = 0;
	}
}

public void controls() {
if (Gdx.input.isKeyPressed(Keys.W) && grounded) {
grounded = false;
speed = 300;
}
}

Perhaps change the guard to if (sprite.getY() <= floor && speed < 0).

Also if the guard is true then explicitly set the y position.

Ideally you should have the guards before you set the Y value. Should be possible with some refactoring.

Thank you,

I made the changes you suggested and it is working fine.

private void gravity() {

	float Y = sprite.getY();

	speed += accel * Gdx.graphics.getDeltaTime();

	if (sprite.getY() <= floor && speed < 0) {
		grounded = true;
		speed = 0;
		sprite.setY(floor);
	}
	Y += speed * Gdx.graphics.getDeltaTime();
	sprite.setY(Y);
}

[.code] and [./code] (Without the dots) are your friends, me too btw :slight_smile: