使我的XNA精灵正确跳转

时间:2012-12-04 10:49:09

标签: c# xna sprite

我一直很难让我的精灵跳起来。到目前为止,我有一段代码,只需点击一下“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;
    }

任何想法和帮助都会受到赞赏,但我希望尽可能地发布我的代码的修改版本。

3 个答案:

答案 0 :(得分:2)

你需要对你的精灵施加一个冲动,而不是你正在做的10的恒定速度。 对于您要做的事情,有一个很好的教程here

答案 1 :(得分: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
}

答案 2 :(得分: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); 
     }
   }

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

同时查看Stack Overflow Physics;)祝你好运。

编辑:那应该是完整的,让我知道事情是怎么回事。