XNA - 对象无法正确移动

时间:2010-10-29 09:36:58

标签: xna

好的,我有一个用户使用箭头键控制的船舶对象。

        if (aCurrentKeyboardState.IsKeyDown(Keys.Left) == true)
            mAngle -= 0.1f;
        else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) == true)
            mAngle += 0.1f;

        if (aCurrentKeyboardState.IsKeyDown(Keys.Up) == true)
        {
           // mSpeed.Y = SHIP_SPEED;
           // mDirection.Y = MOVE_UP;

            velocity.X = (float)Math.Cos(mAngle) * SHIP_SPEED;
            velocity.Y = (float)Math.Sin(mAngle) * SHIP_SPEED;
        }
        else if (aCurrentKeyboardState.IsKeyDown(Keys.Down) == true)
        {
            mSpeed.Y = SHIP_SPEED;
            mDirection.Y = MOVE_DOWN;
        }

以下两种方法属于另一类。

//Update the Sprite and change it's position based on the passed in speed, direction and elapsed time.
    public void Update(GameTime theGameTime, Vector2 velocity, float theAngle)
    {
        Position += velocity * (float)theGameTime.ElapsedGameTime.TotalSeconds;
        shipRotation = theAngle;
    }

    //Draw the sprite to the screen
    public void Draw(SpriteBatch theSpriteBatch)
    {
        Vector2 Origin = new Vector2(mSpriteTexture.Width / 2, mSpriteTexture.Height / 2);

        theSpriteBatch.Draw(mSpriteTexture, Position, new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height), 
            Color.White, shipRotation, Origin, Scale, SpriteEffects.None, 0);
    }

问题在于:程序认为船的前部是侧翼之一,所以在某种程度上,当我按下时它会侧向移动。我不知道为什么会这样。

建议?

3 个答案:

答案 0 :(得分:1)

轻松,玩这两行:

        velocity.X = (float)Math.Cos(mAngle) * SHIP_SPEED;
        velocity.Y = (float)Math.Sin(mAngle) * SHIP_SPEED;

例如,切换sin和cos,并使其中一个为负:

        velocity.X = -(float)Math.Sin(mAngle) * SHIP_SPEED;
        velocity.Y = (float)Math.Cos(mAngle) * SHIP_SPEED;

如果它现在倒退,只需将负片切换为:

        velocity.X = (float)Math.Sin(mAngle) * SHIP_SPEED;
        velocity.Y = -(float)Math.Cos(mAngle) * SHIP_SPEED;

答案 1 :(得分:0)

如果我正确理解您的问题,您可以通过旋转船舶纹理来解决问题。只需在Draw方法中尝试将90或-10添加到shipRotation:

theSpriteBatch.Draw(mSpriteTexture, Position, new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height), 
        Color.White, shipRotation + 90, Origin, Scale, SpriteEffects.None, 0);

theSpriteBatch.Draw(mSpriteTexture, Position, new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height), 
        Color.White, shipRotation - 90, Origin, Scale, SpriteEffects.None, 0);

希望有所帮助!

答案 2 :(得分:0)

然后更改原始精灵以匹配您的程序“认为”是船的前端。