(XNA)速度不会达到0

时间:2014-04-24 12:09:15

标签: c# xna physics velocity

我最近开始使用XNA并遇到一些问题。我有一个精灵,它可以完美地移动一切,但速度不会达到0.它总是2.5或-2.5或类似的东西。

    protected override void Update(GameTime gameTime)
    {

        //Controls
        if (Keyboard.GetState().IsKeyDown(Keys.Right))
        {
            if(vel.X<maxVel)
                vel.X += acc.X * 3 * (float)gameTime.ElapsedGameTime.TotalSeconds;
            player.spritePos.X += vel.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }
        else if (Keyboard.GetState().IsKeyDown(Keys.Left))
        {
            if (vel.X > maxVel*(-1))
                vel.X -= acc.X * 3 * (float)gameTime.ElapsedGameTime.TotalSeconds;
            player.spritePos.X += vel.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }

        else if(vel.X!=0)
        {
        //The velocity should be set to 0 if no button is pressed. It doesn't work.
        //It just stops at 2.5 or -2.5, which leads to slow movement of the  charactereven if no button is pressed.

            if (vel.X > 0)
            {
                player.spritePos.X += vel.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
                vel.X -= acc.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            if (vel.X < 0)
            {
                player.spritePos.X += vel.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
                vel.X += acc.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
        }
        //Collision with Screen Boundaries
        if (player.spritePos.X + player.spriteTexture.Width > GraphicsDevice.Viewport.Width || player.spritePos.X <= 0)
            vel.X = 0;
        Console.WriteLine("Velocity: " + vel.X);
        base.Update(gameTime); 
    }

正如我所说,我是C#/ XNA编码的新手,因此代码非常不干净。

1 个答案:

答案 0 :(得分:2)

原因是这部分:

if (vel.X > 0)
{
    player.spritePos.X += vel.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
    vel.X -= acc.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
}
if (vel.X < 0)
{
    player.spritePos.X += vel.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
    vel.X += acc.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
}

如果我使用你提供的acc.X值重写它,我猜猜gameTime.ElapsedGameTime.TotalSeconds是1/30而XNA每秒运行30次更新:

if (vel.X > 0)
{
    vel.X -= 150 * (float)1/30;
}
if (vel.X < 0)
{
    vel.X += 150 * (float)1/30;
}

这是:

if (vel.X > 0)
{
    vel.X -= 5;
}
if (vel.X < 0)
{
    vel.X += 5;
}

因此,如果vel.X为2.5,则会将其降低到-2.5 然后接下来更新它的-2.5,所以它增加到2.5,并且它在两者之间保持切换,但它永远不会变为0。

要修复它,你可以试试这个:

if (vel.X > 0)
{
    player.spritePos.X += vel.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
    vel.X -= acc.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
    if (vel.X < 0)
        vel.X = 0;
}
if (vel.X < 0)
{
    player.spritePos.X += vel.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
    vel.X += acc.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
    if (vel.X > 0)
        vel.X = 0;
}