Menu
CoddyTech

The Alert State

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 36 of 64.

challenge icon

Challenge

Medium

Alert the turret when the player comes close.

  1. In TurretStates.cs, write AlertState, given the head and the player. Enter: head Color.red, log Intruder!. Tick: face the player around y. Exit: log All clear.
  2. In Turret, write SetState(IState next): the old state's Exit, then the new one's Enter.
  3. Update alerts within range, scans otherwise, then ticks the current state.

Press Play and walk close. Then Check.

Try it yourself

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()
    {
    }
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground