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

}

相关推荐
ljm12005 小时前
QMK启用摇杆和鼠标按键功能
unity·计算机外设·游戏引擎
我命由我123457 小时前
游戏引擎 Unity - Unity 设置为简体中文、Unity 创建项目
c语言·开发语言·c++·unity·visualstudio·c#·游戏引擎
qq_4286396110 小时前
虚幻基础16:locomotion direction
游戏引擎·虚幻
Petrichorzncu1 天前
Games104——网络游戏的进阶架构
游戏引擎
qq_428639611 天前
虚幻基础11:坐标计算&旋转计算
游戏引擎·虚幻
qq_428639611 天前
虚幻基础09:帧运算
游戏引擎·虚幻
学游戏开发的1 天前
UE求职Demo开发日志#19 给物品找图标,实现装备增加属性,背包栏UI显示装备
c++·笔记·游戏引擎·unreal engine
土了个豆子的1 天前
unity中的动画混合树
unity·游戏引擎
学游戏开发的1 天前
UE学习日志#19 C++笔记#5 基础复习5 引用1
c++·笔记·学习·游戏引擎·unreal engine
奔跑的犀牛先生2 天前
unity学习26:用Input接口去监测: 鼠标,键盘,虚拟轴,虚拟按键
unity