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

}

相关推荐
Thomas_YXQ几秒前
Unity3D Addressable 深度优化热更性能消耗
开发语言·3d·unity·微信
程序员也有头发3 分钟前
如何使用AI工具开发Unity
unity·游戏引擎·ai编程
隔窗听雨眠19 分钟前
从零开始的游戏开发入门指南
unity
sinat_3845031136 分钟前
【无标题】
unity·webgl
caimouse40 分钟前
Godot 引擎官方常见问题(FAQ)整理
游戏引擎·godot
一锅炖出任易仙1 小时前
创梦汤锅学习日记day29
学习·ai·ue5·游戏引擎
隔窗听雨眠1 小时前
Unity与Simulink联合仿真:实现无人机目标追踪系统
unity·无人机·cocos2d·simulink
winlife_2 小时前
全程用 AI 做一款商业级手游 · EP10 道具系统:让三个按钮真正改变棋盘
windows·算法·unity·ai编程·游戏开发·mcp·玩法系统
晓13133 小时前
【Cocos Creator 3.x】篇——第三章 脚本编程
前端·javascript·游戏引擎
可别3904 小时前
cesium实现网格化
游戏引擎·cocos2d