如何检查两个触发器是否会碰撞?

时间:2019-09-17 18:44:51

标签: c# unity3d

我用这部分实例化head

GameObject refhead = (GameObject)Instantiate(Resources.Load("Head"), new Vector3(1, 1, 0), Quaternion.Euler(0, 0, 0));
GameObject head = (GameObject)Instantiate(refhead, transform);

但是如何检查它是否与block相撞?我的意思是,如何检查块是否位于坐标(x,y,z)?例如,如果head将与(1, 1, 0)碰撞,我想在head中产生block (trigger),我使用y += 1;。再次需要检查block trigger是否位于(1, 2, 0)中?如果是,则需要检入(1, 3, 0)等。如果block不在此处,则将生成头部。

1 个答案:

答案 0 :(得分:0)

编辑:添加了基于2D和3D物理代码的示例。

2D:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    for name in a['Julian':]:
TypeError: slice indices must be integers or None or have an __index__ method

找到更多信息here

3D:

一种简单的检查方法是使用Physics.CheckSphere在生成对象之前检查GameObject是否已存在于指定位置。

public Vector2 topLeftCorner;
public Vector2 bottomRightCorner;
public int layerMask; // Layer mask to check against (optional)
public float minDepth // Only include objects with a Z coordinate (depth) greater than or equal to this value. (optional)
public float maxDepth // Only include objects with a Z coordinate (depth) less than or equal to this value. (optional)


// casts a box using given coordinates and returns all found colliders
Collider2D[] foundColliders = Physics2D.OverlapAreaAll(topLeftCorner, bottomRightCorner, layerMask, minDepth, maxDepth);

if (foundColliders.Length == 0) {
  // can spawn things
}