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

}

相关推荐
相信神话20218 小时前
第四章:创建《酒魂》项目与场景结构
游戏·游戏引擎·godot·2d游戏开发
mxwin9 小时前
Unity Shader URP 使用模板测试 · 深度测试实现秘境空间效果
unity·游戏引擎·shader
真鬼1231 天前
【Unity 6】Unity6快捷下载,快速下载
unity·游戏引擎
会潜水的小火龙1 天前
unity打包apk报错Failure to initialize问题解决方法
unity·游戏引擎
平行云1 天前
实时云渲染平台数据通道,支持3D应用文件上传下载分享无缝交互
linux·unity·云原生·ue5·gpu算力·实时云渲染·像素流送
Sator11 天前
unity仅用粒子系统实现拖尾
unity·游戏引擎
游乐码1 天前
Unity基础(五)四元数相关
unity·游戏引擎
想做后端的前端1 天前
Unity热更新 - HybridCLR & YooAsset
unity·游戏引擎
鹿野素材屋1 天前
Unity预加载:减少游戏中首次加载资源时的卡顿
windows·游戏·unity
RPGMZ1 天前
RPGMZ游戏引擎事件技巧大全
javascript·游戏引擎·事件·rpgmz·rpgmakermz