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

}

相关推荐
玖玥拾30 分钟前
Unity 3D 笔记(十四)Unity/C# Socket 网络笔记3
服务器·网络·unity·c#
Python私教2 小时前
Godot图片怎么导入?PNG、压缩、Mipmap与Reimport一次讲清
游戏引擎·godot
玖玥拾3 小时前
Unity 3D 笔记(十七)Unity/C# Socket 网络笔记6
服务器·网络·unity·c#
寒水馨4 小时前
Linux下载、安装godot-4.7.1-stable(附安装包Godot_v4.7.1-stable_linux.x86_64.zip)
linux·游戏引擎·godot·游戏开发·2d游戏·3d游戏·godot engine
寒水馨7 小时前
macOS下载、安装godot-4.7.1-stable(附安装包Godot_v4.7.1-stable_macos.universal.zip)
macos·3d·游戏引擎·godot·跨平台·游戏开发·2d
电子云与长程纠缠1 天前
UE中使用TGuardValue与TInlineComponentArray数据结构
开发语言·数据结构·学习·ue5·游戏引擎
玖玥拾1 天前
Unity 3D 笔记(十二)Unity/C# Socket 网络笔记1
网络·unity·c#
玖玥拾1 天前
Unity 3D 笔记(十五)Unity/C# Socket 网络笔记4
服务器·网络·unity·c#
xcLeigh2 天前
Unity基础:创建你的第一个游戏物体——Cube、Sphere与基本3D物体
游戏·3d·unity·教程
ellis19702 天前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#