Menu
CoddyTech

警戒状态

本课属于 Coddy Unity 学习旅程的“Unity 游戏架构”单元。第 36 课,共 64 课。

challenge icon

挑战

中等

玩家靠近时,让炮塔发出警报。

  1. 在 TurretStates.cs 中,编写 AlertState,并传入头部和玩家。进入时:将头部设为 Color.red,并记录日志 Intruder!。更新时:让头部朝向玩家,并围绕 y 轴旋转。退出时:记录日志 All clear。
  2. 在 Turret 中,编写 SetState(IState next):先调用旧状态的 Exit,再调用新状态的 Enter。
  3. 当玩家位于 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 在线编辑器