I am making a 2d Platformer in Java, and for some reason, when the player jumps towards a platform, it gets stuck sometimes. Here is an image of the problem:

As you see, I was making a jump to the top of the platform, but it got stuck.
Here is my collison code for falling/jumping:
if (guy.getJumpState() == false) {
if (canExecuteMovement(0, 8)) {
...
onGround = false;
if (guy.getY() > this.getParent().getHeight() / 2 - 100) {
// if you are in the middle, move the platforms.
for (int i = 0; i < platformCount; i++) {
if (platform[i].getVisibility() == true) {
platform[i].setY(platform[i].getY() - 8);
}
}
} else {
// or just move the guy if not.
guy.moveY(8);
}
} else {
onGround = true;
}
} else {
if (canExecuteMovement(0, -12)) {
if (guy.getY() < this.getParent().getHeight() / 2 - 100) {
// if you are in the middle, move the platforms.
for (int i = 0; i < platformCount; i++) {
if (platform[i].getVisibility() == true) {
platform[i].setY(platform[i].getY() + 12);
}
}
} else {
// or just move the guy if not.
guy.moveY(-12);
}
jumpCount++;
if (jumpCount >= 20) {
jumpCount = 0;
guy.setJumpState(false);
}
} else {
jumpCount = 0;
guy.setJumpState(false);
}
}
Code for moving left and right:
if (guy.getDirection() == "left") {
if (canExecuteMovement(-4, 0)) {
if (guy.getX() < this.getParent().getWidth() / 2) {
// if you are in the middle, move the platforms.
for (int i = 0; i < platformCount; i++) {
if (platform[i].getVisibility() == true) {
platform[i].setX(platform[i].getX() + 4);
}
}
} else {
// or just move the guy if not.
guy.moveX(-4);
}
}
} else if (guy.getDirection() == "right") {
if (canExecuteMovement(4, 0)) {
if (guy.getX() > this.getParent().getWidth() / 2) {
// if you are in the middle, move the platforms.
for (int i = 0; i < platformCount; i++) {
if (platform[i].getVisibility() == true) {
platform[i].setX(platform[i].getX() - 4);
}
}
} else {
// or just move the guy if not.
guy.moveX(4);
}
}
}
And here is canExecuteMovement function:
private boolean canExecuteMovement(int xChange, int yChange) {
int projectedX = guy.getX() + xChange;
int projectedY = guy.getY() + yChange;
Rectangle projectedBounds = new Rectangle(projectedX, projectedY, guy.getWidth(), guy.getHeight());
for (int i = 0; i < platformCount; i++) {
if (projectedBounds.intersects(platform[i].getBounds()) && platform[i].getVisibility() == true) {
return false;
}
}
return true;
}
I really dont know how to tackle this problem, hopefully I can get some enlightenment.
You need to track your allow/deny movement code for
xandyseparately. What’s happening is that if the user can’t move any further right the code stops him altogether. However, he should STILL be able to move up or down.Consider splitting up the conditionals in your code so that when it is assigning the new movement vectors, it sets
xandyseparately, checking for the ability to move inxandyindividually.