2012-12-04 214 views
1

我一直很难让我的精灵跳跃。到目前为止,我有一段代码,只需轻敲一下“W”,就会以等速向上发送精灵。在开始跳跃之后,我需要能够让我的精灵在一定时间或高度回落到地面。精灵的速度2也会不断拉动以模拟某种重力。使我的XNA精灵正常跳转

// 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; 
    } 

任何想法和帮助将不胜感激,但我更愿意修改我的代码张贴,如果可能的话。

+0

2的恒定速度如何发挥作用? – Sean

+0

嗯,这可能不是做这件事的最好方式,但它只是让精灵一直向下传播,除非它与它下面的同步发生冲突:} –

回答

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); 
    } 
    } 

乐趣伪代码和一些实际的代码的小组合,只想补充一点,我没有在上面包括的变量。

也查看堆栈溢出物理;)祝你的游戏好运。

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

+1

谢谢:]我肯定会的,我可以做所有的帮助,我可以:D –

+0

你对其他教程是正确的,我认为它是正确的,但它只是发送精灵到一个预定的高度,无论它跳到哪里从:/ –

+0

尝试实施我的方法,我会编辑它,使其完成,给我一秒钟。 –

2

你需要对你的精灵施加一个冲动,而不是像你正在做的那样等速10。 有一个很好的教程here您正在尝试做什么。

+0

非常感谢您以我的方式发送该教程,它工作得很好 –

+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 
} 
+0

尽管该教程中的示例更好。 – Sean