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

}

相关推荐
NRatel16 小时前
亚马逊S3的使用简记(游戏资源发布更新)
游戏·unity·amazon s3
SmalBox1 天前
【渲染流水线】[几何阶段]-[屏幕映射]以UnityURP为例
unity·渲染
SmalBox2 天前
【渲染流水线】[几何阶段]-[归一化NDC]以UnityURP为例
unity·渲染
SmalBox3 天前
【渲染流水线】[几何阶段]-[图元装配]以UnityURP为例
unity·渲染
霜绛3 天前
Unity:GUI笔记(一)——文本、按钮、多选框和单选框、输入框和拖动条、图片绘制和框绘制
笔记·学习·unity·游戏引擎
谷宇.3 天前
【Unity3D实例-功能-移动】角色行走和奔跑的相互切换
游戏·unity·c#·unity3d·游戏开发·游戏编程
17岁的勇气3 天前
Unity Shader unity文档学习笔记(十九):粘土效果,任意网格转化成一个球(顶点动画,曲面着色器)
笔记·学习·unity·图形渲染·顶点着色器·曲面着色器
benben0444 天前
《Unity Shader入门精要》学习笔记一
unity·shader
YF云飞4 天前
Unity图片优化与比例控制全攻略
游戏·unity·游戏引擎·游戏程序·个人开发
SmalBox4 天前
【渲染流水线】[几何阶段]-[几何着色]以UnityURP为例
unity·渲染