项目文档链接:John Lemon's Haunted Jaunt 项目教程 (适用于3D初学者) - Unity Learn
总代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Observer : MonoBehaviour
{
public Transform player;
public GameEnding gameEnding;
bool m_IsPlayInRange;
void OnTriggerEnter(Collider other)
{
if (other.transform == player)
{
m_IsPlayInRange = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.transform == player)
{
m_IsPlayInRange = false;
}
}
private void Update()
{
if (m_IsPlayInRange)
{
Vector3 direction = player.position - transform.position + Vector3.up;
Ray ray = new Ray(transform.position, direction);
RaycastHit raycastHit;
if (Physics.Raycast(ray,out raycastHit))
{
if(raycastHit.collider.transform == player) {
gameEnding.CaughtPlayer();
}
}
}
}
}
---------------------------------------------------------------------------------------------------------------------------------
Tramsform是Unity的一个组件,是每个游戏对象的跟节点,包含了对象在3D空间的位置、旋转等在C#中使用Unity.Engine即可使用其方法
Verctor3.up是一个静态只读的数下,表示一个向上的方向向量
Ray是Unity.Engine中的一个类 用于表示射线
new一个ray的时候第一个参数是起点 第二个是终点
RaycastHit 是Unity中的结构体,用于存储射线(Ray)的碰撞信息。在本项目中用于制作怪物的视野碰撞。
Physics.Raycast是Unity中用于检测射线是否与场景中的物体发生碰撞的方法,定义在UnityEngine.Physics类中,其第一个参数为射线、第二个参数是用于存储碰撞信息的RaycastHit结构体