簡體   English   中英

如何使一個對象不止一次反彈(Java和LWJGL)?

[英]How to make an object bounce off the ground more than once (Java and LWJGL)?

我正在學習制作簡單的游戲,並且已經成功編碼了非常基本的彈跳動作,其中,按下跳鍵后,玩家回到地面並再次彈跳,從而產生了一種愚蠢的錯覺物理。 我遇到的問題是如何實現它,以便播放器彈跳的速度不是一次而是兩次。 換句話說,現在的代碼非常簡單(稍后再介紹):有一個“已跳轉”標志,一旦跳轉,該標志就為真,並在下一幀進行檢查以查看是否是的,如果是的話,我只是將一些速度添加到y軸速度,然后播放器就會彈起。 但是我似乎找不到編碼第二次彈跳的方法,因為所有事情都是逐幀進行的。 我需要為第二次彈跳添加甚至更低的速度,但是只有在第一次彈跳發生之后,我現在所能獲得的只是這些速度之和,只有一個彈跳。 我不知道該如何誘使程序增加第一個速度,“等待”直到它到達地面,然后添加第二個速度,然后繪制下一幀。

這是一次彈跳的代碼(有效)

       if (y <= 48) { // if player is on the ground
        yspeed = 0;
        y = 48;

        // Friction on ground

        if ((!Keyboard.isKeyDown(Keyboard.KEY_LEFT)) && xspeed < 0) xspeed = xspeed * 0.925;
        if ((!Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) && xspeed > 0) xspeed = xspeed * 0.925;

        if (jumped == true) 
        {
            yspeed += 4.2;
            jumped = false;
        }



        // Jump

        if (Keyboard.isKeyDown(Keyboard.KEY_UP)) 
        {
            yspeed = 10;
            jumped = true;

        }

我將代碼重新排列為如下形式:

boolean airborne = false;

while (true) // the main game loop
{
    if (y <= 48 && airborne) // if player just hit the ground
    {
        //  Perform the "bounce" by changing their vertical direction and decreasing its magnitude
        ySpeed = -ySpeed/2.0;

        //  This will stop them from bouncing infinitely.  After the bounce gets too small,
        //  they will finally land on the ground.  I suggest you play around with this number to find one that works well
        if (Math.abs(ySpeed) <= 0.5)
        {
            //  Stop the bouncing
            ySpeed = 0;

            //  Place them on the ground
            airborne = false;
            y = 48;
        }
    }
    //  Apply friction if they are on the ground
    if (!airborne)
    {
        // Friction on ground
        if ((!Keyboard.isKeyDown(Keyboard.KEY_LEFT)) && xspeed < 0) xspeed = xspeed * 0.925;
        if ((!Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) && xspeed > 0) xspeed = xspeed * 0.925;
    }
    //  Apply a jump action if they're pressing the jump button while on the ground
    if (Keyboard.isKeyDown(Keyboard.KEY_UP) && !airborne) 
    {
        airborne = true;
        yspeed = 10;
    }
}

因此,在這種情況下,您不必跟蹤它們是否剛剛執行了跳轉,而是跟蹤它們是否處於空中。

我假設您有某種重力常數,每幀都要從ySpeed變量中減去。 在每一幀中,如果它們在地面上,或者它們在地面上不施加重力,您都希望將其ySpeed重置為零。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM