I am building a space invader game and I use this linq method to see if the invaders were hit by the player:
foreach (var playerShot in playerShots)
{
if (isWeapon)
{
AliensHit = from invader2 in invaders
where invader2.Area.Contains(playerShot.Area)
select invader2;
}
}
later I have an algorithm that removes the shot and the invader, but that doesn’t matter as
the contains method doesnt work.
I fire a shot which is a bitmap, and it passes through the invader..(its Area property changes correctly, I checked with the debugger, and so the invaders Area changes: they both move.).
Then I checked with a smaller rectangle shot, if the rectangle shot is in the invaders Area and it worked. Both were removed.
AliensHit = from invader in invaders
where invader.Area.Contains(playerShot.Location)
select invader;
Why when I put an area to check the method doesn’t work, I checked for 3 hours with the debugger and found nothing wrong. 🙁
The problem sounds like the use of
Contains. This will returntrueif and only if the shot rectangle is wholly within the invader rectangle. With a smaller playerShot this will happen more often.You probably want to use
.Intersect(playerShot.Area)instead – this will return true if the two areas overlap at all.Edit: As noted by the OP,
.IntersectsWith(playerShot.Area)is the method I meant!