简体   繁体   English

在 Unity 中检测重叠的多边形对撞机

[英]Detecting overlapping polygon2D colliders in Unity

I'm trying to program an isometric building placement script.我正在尝试编写等距建筑放置脚本。 Each building has a PolygonCollider2D component on it with a trigger.每个建筑物上都有一个带有触发器的 PolygonCollider2D 组件。 When placing a new building, I'm trying to check if the PolygonCollider2D of the placed building overlaps with anything else (to check if placement is valid).放置新建筑物时,我试图检查已放置建筑物的 PolygonCollider2D 是否与其他任何东西重叠(以检查放置是否有效)。 My code is as follows:我的代码如下:

Adjust the points of the new placed building collider based on the mouse position根据鼠标位置调整新放置的建筑碰撞器的点数

Vector2[] points = polygonCollider2D.points;
points.SetValue(polygonCollider2D.points[0] + (Vector2)mousePosition, 0);
points.SetValue(polygonCollider2D.points[1] + (Vector2)mousePosition, 1);
points.SetValue(polygonCollider2D.points[2] + (Vector2)mousePosition, 2);
points.SetValue(polygonCollider2D.points[3] + (Vector2)mousePosition, 3);
polygonCollider2D.points = points;

Set up contact filter:设置联系人过滤器:

ContactFilter2D contactFilter2D = new ContactFilter2D();
contactFilter2D.useTriggers = true;
contactFilter2D.SetLayerMask(polygonCollider2D.gameObject.layer);

Check for collisions检查碰撞

List<Collider2D> list = new List<Collider2D>();
Debug.Log(polygonCollider2D.OverlapCollider(contactFilter2D, list));

However if there is already a building there, it still does not register an overlap.但是,如果那里已经有建筑物,它仍然不会记录重叠。 What am I missing / doing wrong ?我错过了什么/做错了什么?

Thanks so much for the help!非常感谢你的帮忙!

Your code which sets the polygon collider points seems to be the issue here.您设置多边形碰撞点的代码似乎是这里的问题。 If that code runs multiple times, it will repeatedly offset the collider further and further away from its original position.如果该代码多次运行,它将反复将碰撞器偏移到越来越远离其原始位置的位置。 You probably don't want to be changing the actual collider;你可能不想改变实际的碰撞器; usually you should move object which has the collider.通常你应该移动有碰撞器的物体。 So you would replace those lines with something like this:所以你可以用这样的东西替换这些行:

gameObject.transform.position = mousePosition;

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

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