简体   繁体   English

Monogame-按下“按下”键而不是“按住”键即可跳转

[英]Monogame - Key 'Pressed' instead of 'Hold' to Jump

Will keep this short and simple: 将使这个简短而简单:

I have a 2D game with a movable character, and I have written some code to allow my player to jump, like so: 我有一个带有可移动角色的2D游戏,并且编写了一些代码来允许我的玩家跳跃,如下所示:

if (Keyboard.GetState().IsKeyDown(Keys.Space) && hasJumped == false)
{
    sound.Play(volume, pitch, pan); // plays jumping sound
    position.Y -= 5f;               // position of jump
    velocity.Y = -10.5f;            // velocity of jump 
    hasJumped = true;
}

However when I hold down the Space Bar , my player will continue to jump when he lands back to the ground, however I want my player to only jump once during the duration of holding down the Space Bar , then having to press it again to jump. 但是,当我按住空格键时 ,我的播放器着陆时将继续跳跃,但是我希望播放器在按住空格键的过程中仅跳一次 ,然后必须再次按以跳动。

I appreciate any help given. 我感谢您提供的任何帮助。

UPDATE 更新

My velocity resets in one of my collision if statements within my Collision() function: Collision()函数中的if语句中,我的速度在一次碰撞中重置:

if (rectangle.touchTopOf(newRectangle))
{
    rectangle.Y = newRectangle.Y - rectangle.Height;
    velocity.Y = 0f;    // velocity reset
    hasJumped = false;
}

As Brian already mentioned you need a variable to remember if the space bar was pressed last tick. 正如Brian提到的那样,您需要一个变量来记住空格键是否在最后一个滴答处按下。 Something like this should fix your problem. 这样的事情应该可以解决您的问题。

if (Keyboard.GetState().IsKeyDown(Keys.Space) && hasJumped == false && !spacebarDown)
{
    sound.Play(volume, pitch, pan); // plays jumping sound
    position.Y -= 5f;               // position of jump
    velocity.Y = -10.5f;            // velocity of jump 
    hasJumped = true;
    spacebarDown = true;
}
if(Keyboard.GetState().IsKeyUp(Keys.Space))
{
    spacebarDown = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM