我一直在尝试解决这个问题,但我真的看不出代码有什么问题。它与我的其他矩形完全相同,但它不起作用。
工作代码:这里的一切工作正常(或多或少)
private void UpdateCollision()
{
// Uses built in rectangle intersect function to determine overlapping
Rectangle rectangle1;
Rectangle rectangle2;
Rectangle rectangle3;
// Creates 1 rectangle for player
rectangle1 = new Rectangle((int)player.Position.X, (int)player.Position.Y, player.Width, player.Height);
// Sets collision btw objs
for (int i = 0; i < enemies.Count; i++)
{
for (int j = 0; j < enemies2.Count; j++)
{
rectangle2 = new Rectangle((int)enemies[i].Position.X, (int)enemies[i].Position.Y, enemies[i].Width, enemies[i].Height);
rectangle3 = new Rectangle((int)enemies2[j].Position.X, (int)enemies2[j].Position.Y, enemies2[j].Width, enemies2[j].Height);
// Determines collision
if (IntersectPixels(rectangle1, playerTextureData, rectangle2, enemyTextureData) && player.PlayerAnimation.Active == true)
{
player.Health -= enemies[i].Damage;
enemies[i].Health = 0;
if (player.Health == 0)
AddMyExplosion(player.Position);
}
if (IntersectPixels(rectangle1, playerTextureData, rectangle3, enemy2TextureData) && player.PlayerAnimation.Active == true)
{
player.Health -= enemies2[j].Damage;
enemies2[j].Health = 0;
if (player.Health == 0)
AddMyExplosion(player.Position);
}
}
}
非工作代码:弹出异常的行是定义rectangle3的地方
// Proj obj collision
for (int i = 0; i < projectiles.Count; i++)
{
for (int j = 0; j < enemies.Count; j++)
{
for (int k = 0; k < enemies2.Count; k++)
{
// Creates col det rectangles
rectangle1 = new Rectangle((int)projectiles[i].Position.X - projectiles[i].Width / 2, (int)projectiles[i].Position.Y - projectiles[i].Height / 2, projectiles[i].Width, projectiles[i].Height);
rectangle2 = new Rectangle((int)enemies[j].Position.X - enemies[j].Width / 2, (int)enemies[j].Position.Y - enemies[j].Height / 2, enemies[j].Width, enemies[j].Height);
rectangle3 = new Rectangle((int)enemies2[k].Position.X - enemies2[k].Width / 2, (int)enemies[k].Position.Y - enemies2[k].Height / 2, enemies2[k].Width, enemies2[k].Height);
//Rectangle 3 is not working//
// Determines col
if (IntersectPixels(rectangle1, projectileTextureData, rectangle2, enemyTextureData))
{
enemies[j].Health -= projectiles[i].Damage;
AddImpact(projectiles[i].Position);
impactSound.Play();
projectiles[i].Active = false;
}
if (IntersectPixels(rectangle1, projectileTextureData, rectangle3, enemy2TextureData))
{
enemies2[j].Health -= projectiles[i].Damage;
AddImpact(projectiles[i].Position);
impactSound.Play();
projectiles[i].Active = false;
}
}
}
}
}
因此,如果有人可以帮助我解决这个问题,我将不胜感激。