CollisionTest();不会像预期的那样工作..只有一个盒子发生碰撞...... 这段代码可能会伤害你的眼睛,它可能是一个不好的方式来做我想要的
Game1.cs
Texture2D boxTexture;
GameObject box, box1, box2;
List <GameObject> boxlist;
Random rand = new Random();
LoadContent()
boxTexture = Content.Load<Texture2D>("box");
for(int i = 0; i < boxlist.Count; i++)
boxlist[i] = new GameObject(boxTexture, new Vector2(rand.Next(100, 1200), rand.Next(500, 600)));
Update()
CollisionTest();
public void CollisionTest()
{
for (int i = 0; i < boxlist.Count; i++)
{
if (player.collisionRect.Intersects(boxlist[i].collisionRect))
{
ground.Y = boxlist[i].collisionRect.Y;
player.setPositionY(0);
}
else
{
ground.Y = 640;
}
}
}
Draw()
for (int i = 0; i < boxlist.Count; i++)
boxlist[i].Draw(spriteBatch);
GameObject.cs
public Rectangle collisionRect
{
get
{
return new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
}
}
答案 0 :(得分:0)
问题在于:
for (int i = 0; i < boxlist.Count; i++)
{
if (player.collisionRect.Intersects(boxlist[i].collisionRect))
{
ground.Y = boxlist[i].collisionRect.Y;
player.setPositionY(0);
}
else
{
ground.Y = 640;
}
}
它仅在列表中的最后一个框上工作,因为即使在检测到碰撞后,您仍会在所有框上执行“else”代码。
假设您在第一个框中检测到碰撞。您执行“碰撞”代码。然后在下一个框中,你不会发生碰撞。您执行“无碰撞”代码。由于您将ground.Y
设置为两个条件的不同值,因此您只会看到上次检查的结果。
正确的方法是这样的:
bool collided = false;
for (int i = 0; i < boxlist.Count; i++)
{
if (player.collisionRect.Intersects(boxlist[i].collisionRect))
{
ground.Y = boxlist[i].collisionRect.Y;
player.setPositionY(0);
collided = true;
//break; //If you want to only handle one collision you can uncomment this
}
}
if (!collided)
ground.Y = 640;