1

我一直很难让我的精灵跳跃。到目前为止,我有一段代码,只需点击“W”,就会以恒定的速度向上发送精灵。我需要能够让我的精灵在开始跳跃后的某个时间或高度回到地面。精灵上还有一个恒定的速度 2 拉动,以模拟某种重力。

// Walking = true when there is collision detected between the sprite and ground

if (Walking == true)
    if (keystate.IsKeyDown(Keys.W))
        {
            Jumping = true;
        }

if (Jumping == true)
    {
        spritePosition.Y -= 10;
    }

任何想法和帮助将不胜感激,但如果可能的话,我更喜欢发布我的代码的修改版本。

4

3 回答 3

2

你需要对你的精灵施加一个脉冲,而不是像你正在做的那样保持 10 的恒定速度。对于您正在尝试做的事情,这里有一个很好的教程。

于 2012-12-04T11:03:08.347 回答
1

我会做这样的事情......

const float jumpHeight = 60F; //arbitrary jump height, change this as needed
const float jumpHeightChangePerFrame = 10F; //again, change this as desired
const float gravity = 2F;
float jumpCeiling;
bool jumping = false;

if (Walking == true)
{
    if (keystate.IsKeyDown(Keys.W))
    {
        jumping = true;
        jumpCeiling = (spritePosition - jumpHeight);
    }
}

if (jumping == true)
{
    spritePosition -= jumpHeightChangePerFrame;
}

//constant gravity of 2 when in the air
if (Walking == false)
{
    spritePosition += gravity;
}

if (spritePosition < jumpCeiling)
{
    spritePosition = jumpCeiling; //we don't want the jump to go any further than the maximum jump height
    jumping = false; //once they have reached the jump height we want to stop them going up and let gravity take over
}
于 2012-12-04T11:05:01.543 回答
1
    public class Player
    {
      private Vector2 Velocity, Position;
      private bool is_jumping; 
      private const float LandPosition = 500f; 

      public Player(Vector2 Position)
      {
         this.Position = new Vector2(Position.X, LandPosition); 
         Velocity = Vector2.Zero;
         is_jumping = false; 
      }
      public void UpdatePlayer(Gametime gametime, KeyboardState keystate, KeyboardState previousKeyBoardState)
      {
       if (!is_jumping)
         if (keystate.isKeyDown(Keys.Space) && previousKeyBoardState.isKeyUp(Keys.Space))
          do_jump(10f); 
       else
       {
        Velocity.Y++; 
        if (Position.Y >= LandPosition)
           is_jumping = false; 
       } 
       Position += Velocity; 

     }

     private void do_jump(float speed)
     {
            is_jumping = true; 
            Velocity = new Vector2(Velocity.X, -speed); 
     }
   }

伪代码和一些真实代码的有趣小组合,只需在顶部添加我没有包含的变量。

还可以查看 Stack Overflow Physics ;) 祝你游戏好运。

编辑:这应该是完整的,让我知道事情进展如何。

于 2012-12-04T11:19:18.403 回答