Menu
CoddyTech

The Knight Attacks

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

challenge icon

Challenge

Medium

Make the knight attack when it catches the player.

  1. In KnightStates.cs, write AttackState: knight.Stop(), and knight.playerHealth.TakeDamage(1) at once, then every second. Farther than attackRange, chase.
  2. In ChaseState, closer than attackRange, change to knight.attack.
  3. In Knight's Awake, add attack = new AttackState(this);.

Press Play and let the knight catch you: the Console shows Player hp: 9. Then Check.

Try it yourself

using UnityEngine;

public class PatrolState : IState
{
    private Knight knight;
    private int next;

    public PatrolState(Knight knight)
    {
        this.knight = knight;
    }

    public void Enter()
    {
    }

    public void Tick()
    {
        if (knight.PlayerDistance() < knight.sightRange)
        {
            knight.machine.ChangeState(knight.chase);
            return;
        }
        Vector3 point = knight.waypoints[next].position;
        if (knight.DistanceTo(point) < 0.3f)
        {
            next = (next + 1) % knight.waypoints.Length;
        }
        knight.WalkTo(knight.waypoints[next].position);
    }

    public void Exit()
    {
    }
}

public class ChaseState : IState
{
    private Knight knight;

    public ChaseState(Knight knight)
    {
        this.knight = knight;
    }

    public void Enter()
    {
    }

    public void Tick()
    {
        float distance = knight.PlayerDistance();
        if (distance > knight.loseRange)
        {
            knight.machine.ChangeState(knight.patrol);
            return;
        }
        knight.WalkTo(knight.player.position);
    }

    public void Exit()
    {
    }
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground