简体   繁体   中英

Collission doesn't seem to work

I'm trying to write a collide between a mob and a player, so I'm trying to add both mobs to a single Rectangle

   protected bool Collide()
    {

        PlayerRect = new Rectangle((int)playerPos.X, (int)playerPos.Y, playerFrameSize.X, playerFrameSize.Y);
        MobsRect = new Rectangle((int)greenMobPos.X + (int)orangeMobPos.X, (int)greenMobPos.Y + (int)orangeMobPos.Y, greenMobFrameSize.X + orangeMobFrameSize.X, greenMobFrameSize.Y + orangeMobFrameSize.Y);

        return PlayerRect.Intersects(MobsRect);
    }

thats my code, but only my 'greenMob' is colliding correctly, second mob 'orangeMob' won't collide. Should I separate them and check for collide for each of them?

protected bool Collide()
{

    PlayerRect = new Rectangle((int)playerPos.X, (int)playerPos.Y, playerFrameSize.X, playerFrameSize.Y);
    MobsRectGreen = new Rectangle((int)greenMobPos.X , (int)greenMobPos.Y , greenMobFrameSize.X , greenMobFrameSize.Y ;
    MobsRectOrange = new Rectangle((int)orangeMobPos.X,  (int)orangeMobPos.Y,  orangeMobFrameSize.X, orangeMobFrameSize.Y);

    return PlayerRect.Intersects(MobsRectGreen ) || return PlayerRect.Intersects(MobsRectOrange )  ;
}

You calculate bounding boxes for each mob and your player. Your player collides with the green one if it intersects the greens bounding box. If it intersects the orange bounding box it collides with that one. The || means logical or.

Your check adds the green and orange X together and the y together and the sizes in x+y together which does not make much sense unless they both are close together and are "one" form. (ie like a house with a roof, each seperately modeled but they move/stay together - boxes make not much sense for roofs though).

It would probably be better to create a method that takes one mob, and checks if the player collides like so:

private bool CollideWithMob(Mob m)
{
    // do the check for player and m here
}

protected bool Collide()
{
    return CollideWithMob(greenMob) || CollideWithMob(orangeMob); 
}

And put the Pos and FrameSize into a class Mob as properties to check. This check would compute the player Rectangle twice if the fist check if false , a combined method wouldn't but its clearer that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM