【问题标题】:Java Game Programming: Smooth JumpingJava 游戏编程:平滑跳跃
【发布时间】:2015-09-19 13:10:03
【问题描述】:

在过去的一个半星期里,我一直在用 Java 和 Swing 从头开始​​编写游戏。到目前为止,游戏一直运行顺利,除了一件事:跳跃。我正在尝试实现抛物线跳跃,以便玩家不只是传送一点点。相反,我希望它看起来很真实。到目前为止,我的代码看起来像这样(这只是跳转方法,只要按下空格、W 或向上键就会调用它):

private void jump(Game game){
    VectorF velocity = new VectorF(0f, 0.1f);       

    int t = 0;

    while(t < 200){
        if(checkTop(game)) break;

        relPos.sub(velocity);
        t++;
    }
}

【问题讨论】:

  • 您有问题吗?
  • 您能否详细说明给定代码的问题是什么?你到底是怎么称呼这个方法的?
  • 顺便说一下,VectorF 是我创建的一个类,用于处理带有浮点数的矢量运动。我还制作了 VectorI,它本质上是相同的,但使用的是整数。
  • mastov 问题是玩家似乎传送了一点点,我用一个带有 input.isKeyPressed(KeyEvent.VK_SPACE) 的 if 语句调用该方法
  • 你应该有一个线程用于每 x 毫秒更新一次玩家的位置,另一个用于重新绘制视图;有了这个,您只需在按下跳跃按钮时改变一次玩家的速度,并在游戏的每个“滴答”中应用重力,就可以让玩家跳跃。

标签: java game-physics


【解决方案1】:

你的游戏应该有一个game loop

通常,一个(非常基本的)游戏循环如下所示:

while (playing) {
    accept_input()
    update_game_logic()
    render()
}

在你的update_game_logic() 函数中,你会有一个更新玩家位置的部分。玩家的位置更新步骤通常看起来像以下几种混合:

// 1. sum up 'effects' on the player
    // think of 'effects' as velocities that we are adding together
    // is jumping? add (0.0, 0.1), 
    // is holding the right-button? add (0.1, 0.0)
// 2. add a gravity effect (0.0, -0.05)?
// 3. sum up all velocity changes and apply them to the player
// 4. check for any collision and prevent it 
    // (straight up adjusting the position out of the colliding object will do for now, this will also stop you from falling through the floor due to gravity)

因为您在每刻都根据速度调整玩家的位置,所以您可以在更新游戏逻辑的同时继续接受输入并渲染屏幕。

编辑:如果你想要一个适当的抛物线弧,上面的“效果”实际上应该是力加在一起导致速度变化(通过加速度),然后以更现实的方式改变位置。查看my similar answer here了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2014-11-12
    • 1970-01-01
    相关资源
    最近更新 更多