0

一段时间以来,我一直在为一个我仍在为学校工作的项目编写代码,即使它已经完成了。

我想制作一个手榴弹,向与之相撞的敌人发射子弹,但我需要使用 atm 的帮助是一次向所有不同方向发射 8 发子弹。

这是我老师给我的代码(我向他寻求帮助)

if (mouse.LeftButton == ButtonState.Pressed)
            {
                Texture2D pewTexture;
                pewTexture = game.Content.Load<Texture2D>("pew");
                game.firingSound.Play();
                //Tweak pews to shoot at mouse, rather than just going straight on the y axis.
                pew = new CPew(game, pewTexture);
                pew.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 10f + spriteVelocity;
                pew.position = position + pew.velocity * 5;

                //easy cheesy way:
                //pew.position = position;
                //pew.position.X += 15f;
                //pew.position.Y -= 20f;





                //super awesome cool way for cool people and celebrities
                pew.position = position +
                    new Vector2(
                        texture.Width * .2f - pew.texture.Width * .2f,
                        -pew.texture.Height);

                game.pews.Add(pew);

                myFiringDelay = 10;


            }
            else
            {
                if (mouse.RightButton == ButtonState.Pressed)
                {
                    float pi2 = (float)Math.PI * 2.0f;
                    int numShots = 10;
                    float pi2overnum = pi2 / numShots;

                    for (int i = 0; i < numShots; i++)
                    {
                        Vector2 direction = PiToVec2(pi2overnum * i);

                        //particles[i].reset(position,direction, vector2.zero, 6);
                        game.pews[i].Reset(pew.position, direction, Vector2.Zero);

                    }

           Vector2 PiToVec2(float piT)
           {
              return new Vector2((float)Math.Sin(piT), (float)Math.Cos(piT));

           }

显然,这将使它在鼠标右键单击时向各个方向射击,但是每次我尝试它时,我的游戏都会直接崩溃然后我们有一个 pew 类,它是子弹,这就是我想同时朝这些方向射击的东西

你们可能无法帮助我向您展示的代码,我花了一段时间寻找一种方法来做到这一点,但我似乎找不到任何东西

以前的示例和/或源代码真的很有帮助,至少是另一种看待这个的方式,谢谢。

当它崩溃时显示给我,它告诉我索引超出范围或为负数,如果你们能告诉我多向子弹的基本代码,我会很高兴

4

1 回答 1

0

您遇到的问题是,当您尝试遍历您的 game.pews 集合时,您正在尝试对集合中的前 10 个项目调用 Reset() 。然而,那里似乎没有 10 个长椅。因此,当您到达最后并尝试访问下一个时,就会出现“索引超出范围”错误。

对于问题的手榴弹部分的 8 颗子弹,我认为您想做这样的事情。

//Once a grenade has collided with an enemy 
float pi2 = (float)Math.PI * 2.0f;
int numShots = 8;
float pi2overnum = pi2 / numShots;

for (int i = 0; i < numShots; i++)
{
   Vector2 direction = PiToVec2(pi2overnum * i);

   pew = new CPew(game, pewTexture);

   pew.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 10f + spriteVelocity;

   //Set the position based off of the grenades last position.
   //Set the direction.
   //Set any other attributes needed.

   game.pews.Add(pew);
}

现在你有八颗子弹从手榴弹爆炸的不同方向移动。要更新它们并绘制它们,我建议使用 foreach 循环,这样您就不必担心“索引超出范围”错误。

foreach CPew pew in game.pews
{
   pew.Update();
}
于 2012-12-02T04:24:36.823 回答