Recap: Guard Dog
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 58 of 71.
This recap puts the chapter together: a chase set as a velocity, a range measured across the ground, damage through a Health script and a knockback impulse.
Challenge
MediumWrite the guard dog: it chases strangers near its kennel.
- In
FixedUpdate(), while the player is underguardRangefromkennel.positionacross the ground, run at the player atspeed, keeping y. - Otherwise run back to the kennel; within 0.3 of it, stand still.
- On bumping the
Player, call itsHealth'sTakeDamage(1)and give it an Impulse ofbiteaway from the dog, flat.
Press Play near the kennel. Then Check.
Try it yourself
using UnityEngine;
public class Dog : MonoBehaviour
{
[SerializeField] private Transform player;
[SerializeField] private Transform kennel;
[SerializeField] private float speed = 3.5f;
[SerializeField] private float guardRange = 6f;
[SerializeField] private float bite = 5f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
// guard the kennel: chase the player near it, or go home
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall3Triggers
Trigger CollidersOnTriggerEnterPickupsCrates Keep the RestKill ZonesEnter and ExitRecap: Key and Door6Raycasts
Physics.RaycastRaycastHitGround Check with a RayLayers and LayerMaskLine of SightOverlapSphere and SphereCastRecap: Laser Tripwire9Enemies
Chase the PlayerChase in RangePatrol and ChaseHealth and DamageBullets That HitKnockbackRecap: Guard DogPractice on your own: Unity playground