您如何看待钥匙是否已被释放?
我想要例如,当用户发布 Left 键时,角色的动画停止并停留在他正在向左/朝向的框架上
这是我的玩家类:
public class Player
{
#region Animation
int currentFrame;
int frameWidth;
int frameHeight;
float timer;
float interval = 65;
#endregion
private Texture2D texture;
private Vector2 position = new Vector2(64, 200);
private Vector2 velocity;
private Rectangle rectangle;
private bool isMoving;
KeyboardState keyState;
public enum playerStates
{
RIGHT,
LEFT,
WALKINGRIGHT,
WALKINGLEFT
}
playerStates currentPlayerState = playerStates.LEFT;
private bool hasJumped = false;
public Vector2 Position
{
get { return position; }
}
public Player(Texture2D newTexture, Vector2 newPosition, int newFrameWidth, int newFrameHeight)
{
texture = newTexture;
position = newPosition;
frameWidth = newFrameWidth;
frameHeight = newFrameHeight;
isMoving = false;
}
public void LoadContent(ContentManager Content)
{
texture = Content.Load<Texture2D>("Mario/full");
}
public void Update(GameTime gameTime)
{
rectangle = new Rectangle(currentFrame * frameWidth, 0, frameWidth, frameHeight);
position = position + velocity;
#region Key Presses
KeyboardState lastKeyState = keyState;
keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Left))
{
//position.X -= 1;
AnimateLeft(gameTime);
currentPlayerState = playerStates.LEFT;
isMoving = true;
}
if (keyState.IsKeyDown(Keys.Right))
{
//position.X -= 1;
AnimateRight(gameTime);
currentPlayerState = playerStates.RIGHT;
isMoving = true;
}
//Check for last keypresses
#endregion
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, rectangle, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 1);
}
#region DrawAnimation
public void AnimateLeft(GameTime gameTime)
{
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
currentFrame++;
timer = 0;
if (currentFrame > 3 || currentFrame < 2)
{
currentFrame = 2;
}
}
}
public void AnimateRight(GameTime gameTime)
{
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
if (timer > interval)
{
currentFrame++;
timer = 0;
if (currentFrame > 5 || currentFrame < 3)
{
currentFrame = 4;
}
}
}
#endregion
}
答案 0 :(得分:2)
如果要检查某个键是否被“切换”或按下,您需要使用两个KeyboardStates
,一个用于当前帧,一个用于最后一帧。看起来你已经有了一些这样的事情,但我会从这里开始
public static KeyboardState CurrentKeyboardState;
public static KeyboardState LastKeyboardState;
在您的更新方法中,您需要设置这些
LastKeyboardState = CurrentKeyboardState;
CurrentKeyboardState = Keyboard.GetState();
为了检查按键是否按下,它必须向下一帧,向上一帧。所以我们可以检查一下。
if (LastKeyboardState.IsKeyDown(Keys.Left) && !CurrentKeyboardState.IsKeyDown(Keys.Left))
//Do Stuff
你可以做我已经做过的事情,并制作一个方便的扩展方法,这样你就可以做if (Keys.Left.IsKeyToggled)
。如果您之前未使用extension methods,则可以阅读here。您将需要一个静态类
public static class Extensions
{
}
只需使用一个包含我们上面使用的代码的方法,将“Class”替换为具有键盘状态的任何类。
public static bool IsKeyToggled(this Keys key)
{
return Class.LastKeyboardState.IsKeyDown(key) && !Class.CurrentKeyboardState.IsKeyDown(key)
}