假设我们有两个物体,一个叫 Cube 和另一个叫 Sphere。为了检测它们是否发生碰撞,我们需要将一个碰撞器组件添加到每个物体上。
在 Unity 中选择 Create → C# Script。
- 将新脚本命名为 CollisionDetection,并将其附加到 Cube 对象上。
using UnityEngine; public class CollisionDetection : MonoBehaviour { void OnCollisionEnter(Collision collision) { if (collision.gameObject.name == "Sphere") { Debug.Log("Cube has collided with the Sphere!"); } } }
这段代码在 Cube 上创建一个新的 OnCollisionEnter 函数。这个函数会在两个物体发生碰撞时被调用。如果与碰撞发生碰撞的物体名称为 “Sphere”,该函数将输出“Cube has collided with the Sphere!”
现在我们已经有了一个脚本来检测碰撞,我们需要将其附加到 Sphere 对象上以完成检测。
- 在 Unity 中选择 Sphere 对象并找到 CollisionDetection 脚本。
- 将该脚本拖放到 Sphere 对象的 Inspector 窗口中。
- 点击 Play 按钮,当 Cube 和 Sphere 相遇时,将看到 Debug.Log 输出“Cube has collided with the Sphere!”。
这是一个简单的示例,演示了如何在 Unity 中检测物体间的碰撞。当然,这只是一个基本示例,您可以根据您的需求进行更复杂的碰撞检测。
Unity 简单实现子弹射击_LuaMin的博客-CSDN博客
Unity 实现简单的发射子弹功能_unity子弹发射_Suval Yao的博客-CSDN博客