基于XNA平铺的运动

Dan*_*hin 1 grid xna dictionary

我正在尝试在XNA中制作一个基于2D平铺的自上而下的游戏.它是16 x 16个图块,每个图块是25个像素.

我有一个字符精灵从(0,0)第一个瓷砖开始,我正在尝试使用键盘从瓷砖到瓷砖移动它.所以在Update方法中,当按下箭头键时,我尝试在位置向量的x或y上加或减25.它在移动时似乎在瓷砖中对齐,但它一次移动大约4-5个瓷砖而不是仅仅1个瓷砖.我已经尝试将它与gameTime.TotalGameTime.TotalSeconds相乘,但它似乎没有帮助.

我对使用XNA有点新意.有没有人有任何教程或可以帮助如何计算运动?提前致谢.

And*_*ell 8

如果您只是检查IsKeyDown每一帧,它会说每个帧都按下了它.按每秒60帧,按一个键将导致它处于几个帧的向下状态.因此,在每一帧你都在移动你的角色!当你放开钥匙的时候 - 他会搬几个方格.

如果要检测每个按键(键进入"向下"状态),您需要这样的事情:

KeyboardState keyboardState, lastKeyboardState;

bool KeyPressed(Keys key)
{
    return keyboardState.IsKeyDown(key) && lastKeyboardState.IsKeyUp(key);
}

override void Update(GameTime gameTime)
{
    lastKeyboardState = keyboardState;
    keyboardState = Keyboard.GetState();

    if(KeyPressed(Keys.Right)) { /* do stuff... */ }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你想在按住键时添加"重复"效果(就像打字时发生的那样),你需要计算时间 - 如下所示:

float keyRepeatTime;
const float keyRepeatDelay = 0.5f; // repeat rate

override void Update(GameTime gameTime)
{
    lastKeyboardState = keyboardState;
    keyboardState = Keyboard.GetState();

    float seconds = (float)gameTime.ElapsedGameTime.TotalSeconds;

    if(keyboardState.IsKeyDown(Keys.Right))
    {
        if(lastKeyboardState.IsKeyUp(Keys.Right) || keyRepeatTime < 0)
        {
            keyRepeatTime = keyRepeatDelay;

            // do stuff...
        }
        else
            keyRepeatTime -= seconds;
    }
}
Run Code Online (Sandbox Code Playgroud)