Reputation: 21
I'm making a 2D platformer and just added gravity & jumping.
It works like it should, however, if the space bar is still held down after the player finishes a jump, the player just keeps jumping while in mid-air.
I know I need to check for whether or not the player is actually on the ground, but when I do it always returns as 'false', as described in my jumping method:
// Controls both falling and the jumping action.
// The MapObject list is a collection of every object the player can
// collide with on that map. Currently it only contains a single 'ground' object.
public void fall(ArrayList<MapObject> objects)
{
int distance = 0;
if (jumpTicks > 0)
{
float jumpHeight = jumpSpeed * (jumpTicks / maxJumpTicks);
System.out.println(jumpTicks + "/" + maxJumpTicks + " = " + jumpHeight);
y -= jumpHeight;
jumpTicks--;
}
else
{
for (MapObject obj : objects)
{
if (this.y + this.height >= obj.y)
{
// This cancels falling if the player's feet are on top
// of the ground, but for some reason setting an 'isOnGround'
// boolean to 'true' here and checking for it in the 'jump()'
// method does not work, it's always 'false'.
return;
}
distance = obj.y - (this.y + this.height);
}
if (distance > fallSpeed)
{
y += fallSpeed;
}
else
{
y += distance;
}
}
}
// This doesn't make the player jump, it just adds jump time to the player
// if it's not already jumping.
public void jump()
{
if (jumpTicks > 0)
{
return;
}
this.jumpTicks = maxJumpTicks;
this.jumpSpeed = 10;
}
Upvotes: 2
Views: 732
Reputation: 1261
Before you change his speed, check his y
value for the floor
function jump() {
if (jumpTicks > 0) {
return;
}
if (this.y === floorY) {
this.jumpTicks = maxJumpTicks;
this.jumpSpeed = 10;
}
}
Upvotes: 1