简体   繁体   中英

Create Java 2D gravity?

I'm creating java game (I'm a beginner with this for now) and I'd like to start with some kind of platform game.

I'd like to know how I can make the player jump (I know how to move him up and down), but I don't know how how to make him go back down after going up.

Here is my code:

    public void keyPress() {
        if (listener.arrowUp) {
        Jump();
    }
}

private void Jump() {
    if(player.get(1).getPosY() > maxJump) {
        player.get(1).moveY(-10);
    } else if(player.get(1).getPosY() == maxJump) {
        player.get(1).moveY(85);
    }
}

So.. the player moves -10px upwards as long as i press 'w' and when he hits maxJump (which is 375 and players position at the start is 465) he "teleports" back to 465 instead of sliding back down like he does when going up.. It's really hard to explain this without a video, but i hope somebody understands and can help me with this.

This question gives a basic answer to yours. Now in your jump function, you have to set the vertical_speed only once and only call fall() every frame and add some moveY .

Here are two alternatives:

Option 1. Simulating some very simple physics. You add forces to your player, so pressing the up arrow will add a force that makes the player move upwards. Gravity is constantly applied and thus it will gradually cancel out the force you applied when the up arrow was pressed. Perhaps you only want to use forces in the vertical direction you do something like this:

// Each frame
if(notOnTheGround){
    verticalVelocity -= GRAVITATIONAL_CONSTANT;
}

// When user jumps
vertivalVelocity += JUMP_FORCE;

Option 2. An alternative is to kind of animate the jumps using projectile motion .

// Each frame
if(isJumping){
    verticalVelocity = initialVelocity*sin(angle) - g*animationTime;
    animationTime += TIME_STEP;
}

// When user jumps
isJumping = true;
animationTime = 0;
initialVelocity = ... // calculate initial velocity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM