开发者

Rectangle Contains problem

开发者 https://www.devze.com 2023-02-25 20:02 出处:网络
I am building a space invader game and I use this linq method to see if the invaders were hit by the player:

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 return true if 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!


If your frame rate is too low, then the shot may be travelling far enough in every time step as to completely jump over an invader.

One way to solve this would be to increase the physics FPS significantly, but only draw every 1 frame in 10 physics frames.

Another (probably better) way would be to see if the line (oldShotX, oldShotY)->(newShotX, newShotY) intersects an invader rectangle. But it's much easier to just crank up the FPS.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号