rustum 发表于 2022-9-25 17:46

Unity 中的碰撞

想在 Unity 中实现碰撞来选择物体,所以先研究一下碰撞。

[*]新建两个cube
[*]其中一个的 Box Collider 选上 IsTrigger
[*]添加上代码,写下 OnTriggerEnter Event
[*]让它们碰撞起来
public class BumpIntoSomething : MonoBehaviour
{
    public float speed = 2000;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
      transform.Translate(Vector3.forward * Time.deltaTime * speed);
    }

    private void OnTriggerEnter(Collider other) {
      Debug.Log( other.name );
    }
}
即使碰撞发生,但是 OnTriggerEnter 并没有被调用。
Collider vs Rigidbody

发现不行,然后回头去看官方文档Collider.OnTriggerEnter(Collider),原来:
Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component.一定要有 Rigidbody 这个 component,再搜了一下:
No, at least one must have a rigidbody attached.两个物体之间必须要有一个 Rigidbody,至于原理,大概是因为碰撞是物理的,和 physics system 相关,所以一定要 Rigidbody,尝试把 Rigidbody 添加到两个物体上面任意一个,都 work。
随意的给另一个物体添加了代码:
public class ChangeColorWhenCollide : MonoBehaviour
{
    private void OnTriggerEnter(Collider other) {
      Debug.Log( "cube being collided" );
      var renderer = GetComponent<Renderer>();
      renderer.material.SetColor("_Color", Color.red);
    }
}



参考:

[*]Collider.OnTriggerEnter(Collider)
页: [1]
查看完整版本: Unity 中的碰撞