I have scoured through the internet to find a solution of this but this is the only solution that I could find but it cancels the yMove += jumpingVelocity * deltatime
as soon as collision is not detected anymore thus it instantly just goes down. If I remove the isJumping
the character continues to go up as long as the jump button is pressed.
xMove = 0;
yMove = 0;
if (handler.getKeyManager().left) xMove -= movementVelocity * deltaTime;
if (handler.getKeyManager().right) xMove += movementVelocity * deltaTime;
if (handler.getKeyManager().jump && onFloor && !isJumping) {
yMove += jumpingVelocity * deltaTime;
isJumping = true;
}
else{
isJumping = false;
}
// gravity
yMove += gravity * deltaTime;
This is the code that updates the player position
public void moveX(){
if (xMove > 0){
int tx = (int) (x + xMove + bounds.x + bounds.width) / Tile.TILEWIDTH;
if (!collisionWithTile(tx,(int) (y + bounds.y) / Tile.TILEHEIGHT) && !collisionWithTile(tx,(int) (y + bounds.y + bounds.height) / Tile.TILEHEIGHT) && tx < handler.getWorld().getWidth()){
x += xMove;
}
else{
x = tx * Tile.TILEWIDTH - bounds.x - bounds.width - 1;
}
}
else if (xMove < 0){
int tx = (int) (x + xMove + bounds.x) / Tile.TILEWIDTH;
if (!collisionWithTile(tx,(int) (y + bounds.y) / Tile.TILEHEIGHT) && !collisionWithTile(tx,(int) (y + bounds.y + bounds.height) / Tile.TILEHEIGHT)){
x += xMove;
}
else{
x = tx * Tile.TILEWIDTH + Tile.TILEWIDTH - bounds.x;
}
}
}
public void moveY(){
if (yMove < 0){
int ty = (int) (y + yMove + bounds.y) / Tile.TILEWIDTH;
if (!collisionWithTile((int) (x + bounds.x) / Tile.TILEWIDTH, ty) && !collisionWithTile((int) (x + bounds.x + bounds.width) / Tile.TILEWIDTH, ty)){
y += yMove;
}
else{
y = ty * Tile.TILEHEIGHT + Tile.TILEHEIGHT - bounds.y;
}
}
else if (yMove > 0){
int ty = (int) (y + yMove + bounds.y + bounds.height) / Tile.TILEWIDTH;
if (!collisionWithTile((int) (x + bounds.x) / Tile.TILEWIDTH, ty) && !collisionWithTile((int) (x + bounds.x + bounds.width) / Tile.TILEWIDTH, ty)){
y += yMove;
onFloor = false;
}
else {
y = ty * Tile.TILEHEIGHT - bounds.y - bounds.height - 1;
onFloor = true;
}
}
}
onFloor
andisJumping
should be integrated in one state machine, not two boolean variables. Gravity should affect velocity, not position. When the player releases the jump button, instead of assigningisJumping
a false value, it should go to the falling state. \$\endgroup\$