如何在背景中出现弹孔? (XNA C#)

时间:2014-10-25 09:34:04

标签: c# xna

一旦我开枪,我正试图在背景中出现弹孔。

到目前为止游戏的工作方式如下: 1.装载喷枪精灵 2.单击鼠标左键加载gunFlame sprite并播放声音 3.释放鼠标左键加载枪精灵(没有火焰) 我想要实施的下一步是在距离枪相对距离的背景上留下一些弹孔。

class Gun
    {
        Texture2D gun, gunFlame, gunObject, bulletHole, hole;
        Vector2 position, bulletHolePosition;
        SoundEffect shotSound, fallSound;
        MouseState currentMouseState, previousMouseState;

        public Gun(ContentManager Content)
        {
            bulletHole = Content.Load<Texture2D>("bullethole");
            bulletHolePosition = new Vector2(position.X + 3, position.Y + 3);
            gun = Content.Load<Texture2D>("Gun");
            position = new Vector2(10, 10);
            gunFlame = Content.Load<Texture2D>("gunFlame");
            shotSound = Content.Load<SoundEffect>("gunshot");
            fallSound = Content.Load<SoundEffect>("bullet-fall");
            gunObject = gun;

        }

        public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(gunObject, position, Color.White);

        }


        public void Update(GameTime gameTime)
        {
            // Keep track of the previous state to only play the effect on new clicks and not when the button is held down
            previousMouseState = currentMouseState;
            currentMouseState = Mouse.GetState();
            if (currentMouseState.LeftButton == ButtonState.Pressed && previousMouseState.LeftButton != ButtonState.Pressed)
            {
                gunObject = gunFlame;
                hole = bulletHole;
                shotSound.Play();
                fallSound.Play();           
            }
            else if(currentMouseState.LeftButton == ButtonState.Released)
            {
                 gunObject = gun;
            }  
        }

1 个答案:

答案 0 :(得分:1)

我在你的代码中看到了一些问题,这让我怀疑你甚至可以执行它,例如在你的构造函数中:

bulletHolePosition = new Vector2(position.X + 3, position.Y + 3);
gun = Content.Load<Texture2D>("Gun");
position = new Vector2(10, 10);

您在初始化之前使用的是position对象,是否有意?

无论如何,为了创建弹孔你可以做的是有一个列表(或阵列或你最喜欢的任何一个),包含洞应该在你的背景中的位置。

您可以在if (currentMouseState.LeftButton == ButtonState.Pressed && previousMouseState.LeftButton != ButtonState.Pressed)语句中为集合添加漏洞。

之后,在Draw方法上,只需遍历集合并在每个位置绘制bulletHole纹理。

所以基本上用Vector2 bulletHolePosition替换IList<Vector2> bulletHolePositions

示例:

Vector2 position;
IList<Vector2> bulletHolePositions;

在构造函数中:

bulletHolePositions = new List<Vector2>;

Update方法中:

if (currentMouseState.LeftButton == ButtonState.Pressed && previousMouseState.LeftButton != ButtonState.Pressed)
{
    bulletHolePositions.Add(new Vector2(currentMouseState.X, currentMouseState.Y));
    //...
}
//...

最后,在Draw方法中:

spriteBatch.Draw(gunObject, position, Color.White);
foreach(var holePosition in bulletHolePositions)
    spriteBatch.Draw(bulletHole , position, Color.White);

请注意,如果屏幕上有很多这样的内容,您的游戏效果可能会下降。

如果您需要更多帮助,请向我们提供有关您遇到问题的详细信息。