检查两个碰撞器是否与Raycast重叠?

时间:2017-03-08 07:21:59

标签: c# unity3d collision-detection raycasting

尝试通过使用距离很小或没有距离的Raycast Sphere来检测对象是否与另一个对象重叠。我的相关代码如下:

//Check at location using Stationary Spherecast, apply damage effect if its a unit
        if (Physics.SphereCast (transform.position, 3, Vector3.up, out hit, 1)) {
            Debug.Log ("In Spherecast");
            if (hit.transform.CompareTag ("Enemy unit") || hit.transform.CompareTag ("Player Unit")) {
                Debug.Log ("In Spherecast's If");
                int Dmg = MM.MoveStat (Ours, SM.selected.GetComponent<EidolonClass> (), hit.transform.gameObject.GetComponent<EidolonClass> ());
                hit.transform.gameObject.GetComponent<EidolonClass> ().TakeDamage (Dmg);
            }
        }

但是,目前,这些Debug.Log语句都没有输出到控制台。是否有一些我对球体播放或其构造者的误解?

2 个答案:

答案 0 :(得分:3)

  

尝试检测对象是否与另一个对象重叠

使用Physics.OverlapXXX函数之一。它们中有很多但是如果您正在寻找Sphere,则应使用Physics.OverlapSphere

为了提高性能,请使用以NonAlloc结尾的那些。

Physics.OverlapSphereNonAlloc应该没问题。只需检查它返回的是&gt; 0

Collider[] colliders = new Collider[5];

void Update()
{
    if (Physics.OverlapSphereNonAlloc(transform.position, 3, colliders) > 0)
    {
       //Overlaps!
    }
}

注意

确保将一个collier附加到要检查它们彼此重叠的两个游戏对象。

修改

如果您还需要访问Colliders

Collider[] colliders = new Collider[5];

void Update()
{
    int hitCount = Physics.OverlapSphereNonAlloc(transform.position, 3, colliders);

    if (hitCount > 0)
    {
        Debug.Log("Touching!");

        for (int i = 0; i < hitCount; i++)
        {
            Collider C = colliders[i];

            Debug.Log("In Foreach for: " + C.name.ToString());
            if (C.transform.CompareTag("Enemy Unit"))
            {
                Debug.Log(C.name.ToString() + " Is an enemy");

                //...
            }
        }
    }
    else
    {
        Debug.Log("Not Touching!");
    }
}

答案 1 :(得分:0)

找到一个有效的解决方案,从程序员和rutter建议的解决方案中获取想法,以及在本网站和官方Unity论坛上四处寻找能够找到我所需要的解决方案的解决方案。下面是完成的代码片段:

Collider[] collisions = Physics.OverlapSphere(transform.position,.75f);
		foreach (Collider C in collisions) {
			Debug.Log("In Foreach for: " + C.name.ToString());
			if (C.transform.CompareTag ("Enemy Unit")) {
				Debug.Log (C.name.ToString () + " Is an enemy");
				int Dmg = MM.MoveStat (Ours, SM.selected.GetComponent<EidolonClass> (), C.transform.gameObject.GetComponent<EidolonClass> ());
				C.transform.gameObject.GetComponent<EidolonClass> ().TakeDamage (Dmg);
			}
		}