简体   繁体   English

创建Java 2D重力?

[英]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. 我正在创建Java游戏(我现在是这个游戏的初学者),我想从某种平台游戏开始。

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. 所以..只要我按下“ w”,玩家便向上移动-10px,当他达到maxJump(375且玩家起始位置为465)时,他“传送”回465,而不是像他一样向下滑动没有视频时,很难解释这一点,但我希望有人能理解并能帮助我。

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 . 现在,在跳转功能中,您只需设置一次vertical_speed ,并且每帧只调用fall()并添加一些moveY

Here are two alternatives: 这里有两种选择:

Option 1. Simulating some very simple physics. 选项1.模拟一些非常简单的物理过程。 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 . 选项2。一种替代方法是使用弹丸运动为跳跃动画

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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