XNA 3.5发射坦克炮

本文关键字:坦克炮 发射 XNA | 更新日期: 2023-09-27 18:20:15

我有一个坦克车身的2D图像(自上而下),可以在屏幕上左右移动。在顶部,有第二个坦克炮塔的图像。随着用户鼠标沿Y轴移动,可以在屏幕边缘旋转此转塔。

当用户按下"Enter"时,会出现一个子弹,并以炮塔的角度在屏幕上移动。然而,虽然角度很好,但子弹的位置似乎变化很大。有时,它会定位在它应该定位的位置(在大炮的中心),然而,当你移动鼠标时,它似乎会偏离位置。


编辑:出于某种奇怪的原因,我的照片似乎没有出现——所以这里有一个直接链接:http://img824.imageshack.us/img824/7093/khte.png

编辑代码:

Tank Fire
     if (keyBoardState.IsKeyDown(Keys.Enter))
                {
                    shell.Initialize(rotation, new Vector2(location.X + 25, location.Y - 15));
                    shell.makeAlive();
                }

(它是用坦克的位置(+25,-25)初始化的,所以它出现在草皮的末端。将其设置在储罐位置(外壳。初始化(旋转,位置);)似乎对偏移量没有影响。)

项目符号/外壳:

public void Update(GameTime gameTime)
    {
        if (alive)
        {
            movement.X -= speed * (float)Math.Cos(rotation);
            movement.Y -= speed * (float)Math.Sin(rotation);
            location.X += (int)movement.X;
            location.Y += (int)movement.Y;
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        if (alive)
        {
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
            spriteBatch.Draw(texture, location, null, Color.White, rotation - MathHelper.PiOver2, new Vector2(texture.Width / 2, texture.Height / 2), 1.0f, SpriteEffects.None, 0f);
            spriteBatch.End();
        }
    }

XNA 3.5发射坦克炮

如果你试图让你的子弹绕着你的坦克旋转,我个人会把子弹画在坦克顶部,做与你发射子弹后完全相同的事情(但幅度更大)来取代它,

但如果你想使用SpriteBatch.Draworigin参数,我会想象它会是这样的:

给定以下数据点:

this.origin = new Vector2(texture.Width / 2, texture.Height / 2);
tank.origin = new Vector2(texture.Width / 2, texture.Height / 2);
// and this is what you'd pass into your sprite-batch.draw method
originToDraw = (tank.position + tank.origin)-(this.position + this.origin)

你还必须将子弹的位置初始化到合适的起点。因为我实际上不知道旋转是从哪里来的,我不能确定,但如果是你的坦克和鼠标之间的角度,我会想象下面的

this.startingPosition = tank.position + tank.origin - this.origin

我假设shellBullet实例,如果是的话,您的问题是Bullet类中的根源。它应该在LoadTextures方法中设置此值

public void LoadTextures(Texture2D texture)
{
    this.texture = texture;
    this.origin = new Vector2(texture.Width, texture.Height);
}

并且在Bullet.Draw方法中增加了一点:

spriteBatch.Draw(texture, location, null, Color.White, rotation - 1.5f, origin, 1.0f, SpriteEffects.None, 0f);

将1.5f更改为MathHelper.PiOver2,当您想将某物旋转90度时,更准确

这里有一个严重的舍入问题。

您可以用浮点计算速度,但对于子弹的位置,可以切换到整数。问题是,当平均时,任何给定的子弹都会出现错误,每次都会向上取整或向下取整。

让我们举一个极端的例子:子弹发射时偏离垂直轴25度,每个更新周期以两个像素的速度移动。奇怪的是,子弹直接沿着轴线飞了下来。

或者更极端的情况。速度为每周期1/3像素。子弹静止不动。