基础交互入门(碰撞交互事件OnTriggerEnter和OnCollisionEnter)
一、碰撞交互事件OnTriggerEnter
1、在场景中添加两个几何体(例如Cube和Sphere)

2、添加Rigidbody(刚体)component
点击Cube(正方体)对象,在面板找到这个按钮,添加component

搜索Rigidbody

默认状态下collider(碰撞)是被开启的。

3、创建C#脚本,增加OnTriggerEnter事件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class e : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("碰撞发生啦!");
var renderer = GetComponent<Renderer>();
renderer.material.SetColor("_Color", Color.blue);
}
}
4、将shpere(球体)设置为触发器,不需要添加刚体和代码。

5、将正方体摆放在球体上方,自由降落,可以看到穿过球体的过程中执行了碰撞交互事件(变蓝色)

二、碰撞交互事件OnCollisionEnter
1、将Is Trigger取消勾选。
2、将代码修改为:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class e : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
Debug.Log("碰撞发生啦!");
var renderer = GetComponent<Renderer>();
renderer.material.SetColor("_Color", Color.blue);
}
}
三、总结
(1)OnTriggerEnter方法使用时,被动碰撞体必须包含一个 Collider(碰撞),一个Rigidbody(刚体),被动碰撞体上需要启用isTrigger(触发器)。刚体不能勾选IsKinematic。
(2)如果两个GameObject都有Collider都开启isTrigger时,或者两个GameObject都没有Rigidbody组件时,碰撞将不发生。
(3)当触发OnTriggerEnter方法,OnCollisionEnter则不会被执行。
官方:Collider.OnTriggerEnter(Collider)
官方:Collider.OnCollisionEnter(Collision)
&spm=1001.2101.3001.5002&articleId=128321727&d=1&t=3&u=65cf1173cae8483b9c2ae6179bb78095)
1387

被折叠的 条评论
为什么被折叠?



