简体   繁体   English

Collission似乎不起作用

[英]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 我正在尝试在生物和玩家之间发生碰撞,所以我试图将两个生物都添加到单个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. 多数民众赞成在我的代码,但只有我的“ greenMob”正确碰撞,第二个暴徒“ orangeMob”不会碰撞。 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. 您的支票将绿色和橙色X以及y以及x + y的大小加在一起,除非它们彼此靠近且为“一个”形式,否则这没有多大意义。 (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. 并将Pos和FrameSize作为要检查的属性放入class Mob This check would compute the player Rectangle twice if the fist check if false , a combined method wouldn't but its clearer that way. 如果拳头检查是否为false,则此检查将对玩家Rectangle进行两次计算,但组合方法不会,但这样会更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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