The Knight Attacks
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 40 of 64.
Challenge
MediumMake the knight attack when it catches the player.
- In
KnightStates.cs, writeAttackState:knight.Stop(), andknight.playerHealth.TakeDamage(1)at once, then every second. Farther thanattackRange, chase. - In
ChaseState, closer thanattackRange, change toknight.attack. - In
Knight's Awake, addattack = 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot7State Machines
States as ClassesThe Alert StateA State MachineTransitionsEnemy BrainsThe Knight AttacksRecap: Door States2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground