警戒状态
本课属于 Coddy Unity 学习旅程的“Unity 游戏架构”单元。第 36 课,共 64 课。
挑战
中等玩家靠近时,让炮塔发出警报。
- 在
TurretStates.cs中,编写AlertState,并传入头部和玩家。进入时:将头部设为Color.red,并记录日志Intruder!。更新时:让头部朝向玩家,并围绕 y 轴旋转。退出时:记录日志All clear。 - 在
Turret中,编写SetState(IState next):先调用旧状态的 Exit,再调用新状态的 Enter。 - 当玩家位于
range范围内时发出警报,否则进行扫描,然后更新当前状态。
按下 Play,然后走近。接着按下 Check。
亲手试试
using UnityEngine;
public class ScanState : IState
{
private Transform head;
private float angle;
private float direction = 1f;
public ScanState(Transform head)
{
this.head = head;
}
public void Enter()
{
angle = 0f;
direction = 1f;
head.GetComponent<Renderer>().material.color = Color.green;
}
public void Tick()
{
angle += 90f * direction * Time.deltaTime;
if (angle > 45f)
{
angle = 45f;
direction = -1f;
}
if (angle < -45f)
{
angle = -45f;
direction = 1f;
}
head.localRotation = Quaternion.Euler(0f, angle, 0f);
}
public void Exit()
{
}
}
Unity 游戏架构中的所有课
自己练习: Unity 在线编辑器