2

我是编程世界的初学者,现在我正在尝试用 C# 进行 XNA 编程,现在我正在开发一个基本游戏,玩家是飞机或宇宙飞船,你必须击落流星。

目前我正在尝试盒子碰撞检测,但我不太清楚,我不知道如何获取列表中每个项目的位置,我需要你的帮助!

所以基本上我有一个shiptexture和一个meteortexture。modeltexture 被绘制了 10 次,并获得随机位置。我想在每颗流星周围制作矩形,但我不知道怎么做。我尝试使用下面显示的 foreach 循环,但是当我与它碰撞时只有一颗流星起作用。对不起,如果我的英语不是最好的,我感谢大家的帮助!

List<Vector2> meteor_pos = new List<Vector2>();

              //loadcontent
            for (int i = 0; i < 10; i++)
            {
                meteor_pos.Add(new Vector2(myRnd.Next(800), myRnd.Next(600)));
                double tmp_angle = (myRnd.Next(1000) * Math.PI * 2) / 1000.0;
                double tmp_speed = 0.5 + 3.0 * (myRnd.Next(1000) / 1000.0);
                meteor_speed.Add(new Vector2((float)(tmp_speed * Math.Cos(tmp_angle)),
                (float)(tmp_speed * Math.Sin(tmp_angle))));
            }

              //protected override void Update(GameTime gameTime)
              for (int i = 0; i < meteor_pos.Count; i++)
                {
                    meteor_pos[i] += meteor_speed[i];
                    Vector2 v = meteor_pos[i];
                    //Outside the screen?
                    if (v.X < -80)
                        v.X = graphics.GraphicsDevice.Viewport.Width + 80;
                    if (v.X > graphics.GraphicsDevice.Viewport.Width + 80)
                        v.X = -80;
                    if (v.Y < -60)
                        v.Y = graphics.GraphicsDevice.Viewport.Height + 60;
                    if (v.Y > graphics.GraphicsDevice.Viewport.Height + 60)
                        v.Y = -60;
                    //Uppdate the list
                    meteor_pos[i] = v;

               }
                foreach (var item in meteor_pos)      
                 {
                     meteor_rect = new Rectangle((int)item.X, (int)item.Y, gfx_meteor.Width, gfx_meteor.Height);
                 }

                gfx_rect = new Rectangle((int)position.X, (int)position.Y, gfx.Width, gfx.Height);

                if (gfx_rect.Intersects(meteor_rect))
                {
                    position.X = 0;
                    position.Y = 0;
                }

    //protected override void Draw(GameTime gameTime)

                for (int i = 0; i < meteor_pos.Count; i++)
            {
                spriteBatch.Draw(gfx_meteor, meteor_pos[i], null, Color.White, 0,
                new Vector2(gfx_meteor.Width / 2, gfx_meteor.Height / 2), 1.0f, SpriteEffects.None, 0);
            }}
4

1 回答 1

1

您的方法非常混乱,您将要创建一个类,至少可能是一个处理位置和其他一些基本信息的精灵类。

但是,要解决您当前的问题,您将在 foreach 循环中覆盖 meteor_rect 的值,然后只在最后检查一次碰撞。

所以切换你的代码看起来像这样:

gfx_rect = new Rectangle((int)position.X, (int)position.Y, gfx.Width, gfx.Height);

foreach (var item in meteor_pos)      
    {
        meteor_rect = new Rectangle((int)item.X, (int)item.Y, gfx_meteor.Width, gfx_meteor.Height);

        if (gfx_rect.Intersects(meteor_rect))
            {
                position.X = 0;
                position.Y = 0;
            }
    }

但就像我说的,请查看一个基本教程来帮助你:)

于 2012-10-26T15:40:00.527 回答