Unity 触发检测与碰撞检测的示例

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Collider_Class : MonoBehaviour {

// 用于Collider类的测试

public GameObject OneBullet;

Transform Father;

void Start ()

{

Father = GameObject.FindGameObjectWithTag("Player").transform;

}

void Update ()

{

if (Input.GetKeyDown(KeyCode.F))

{

GameObject NewBullet = GameObject.Instantiate<GameObject>(OneBullet, Father);

NewBullet.transform.GetComponent<Rigidbody>().AddForce(NewBullet.transform.forward * 2000,ForceMode.Force);//增加力

NewBullet.name = "Monster";

Destroy(NewBullet,5f);//摧毁

}

}

#region// 触发器的三个事件

// 进入触发范围会调用一次

void OnTriggerEnter(Collider other)

{

Debug.Log("有人进入触发区,名字是:"+ other.transform.gameObject.name);

}

// 当持续在触发范围内发生时调用

void OnTriggerStay(Collider other)

{

Debug.Log("怪兽持续在触发区,名字是" + other.transform.gameObject.name);

}

// 离开触发范围会调用一次

void OnTriggerExit(Collider other)

{

Debug.Log("怪兽离开触发区,名字是" + other.transform.gameObject.name);

}

#endregion

#region //碰撞相关的三个方法

// 碰撞开始会调用一次

void OnCollisionEnter(Collision other)

{

Debug.Log("进入碰撞区,碰撞到的物体叫:"+ other.transform.gameObject);

other.transform.GetComponent<Rigidbody>().AddTorque(new Vector3(0,10,0),ForceMode.Impulse);//让他旋转起来

}

// 当碰撞持续发生时调用

void OnCollisionStay(Collision other)

{

//检测和谁发生碰撞

if (string.Equals("Monster", other.gameObject.name))//如果名字匹配

{

print("怪兽撞击我们的隔离墙");

}

Debug.Log("持续碰撞,碰撞到的物体叫:" + other.transform.gameObject);

}

// 碰撞结束会调用一次

void OnCollisionExit(Collision other)

{

Debug.Log("离开碰撞,离开碰撞的物体叫:" + other.transform.gameObject);

}

#endregion

}

相关推荐
老朱佩琪!3 小时前
Unity备忘录模式
java·unity·备忘录模式
一帘多啦A梦3 小时前
解决unity2022.3.x版本项目使用vs无法生成解决方案的问题
unity·vs
weixin_424294676 小时前
Unity LocalPosition 和 Position 的区别?还有其他的Position 没?
unity·游戏引擎
UX20176 小时前
Git LFS 管理 Unity 大文件
git·unity
nnsix6 小时前
Unity WebGL端调用Windows窗口选择文件
unity·游戏引擎·webgl
向宇it6 小时前
【unity游戏开发——网络】使用Unity+PurrNet+Heathens+Steam,在 Unity 中通过 Steam与你的朋友建立联系
网络·游戏·unity·c#·游戏引擎·steam
nnsix7 小时前
Unity 反编译dll(Windows平台)
unity
XR技术研习社7 小时前
四种安装特定版本Package的方法
unity·ar·xr·vr
dzj20218 小时前
Unity行为脚本与编辑器脚本的解耦例子之一
unity·解耦·编辑器脚本·行为脚本
技术小甜甜10 小时前
【Godot】【入门】编辑器界面速通:场景/节点/Inspector/信号(30 分钟上手不迷路)
编辑器·游戏引擎·godot