Recap: Guard Dog
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 55 of 63.
Challenge
MediumA guard dog keeps strangers away from its kennel. Write the Dog script. The Inspector gives it player, kennel (the red mat in front of the doghouse), speed (3.5), guardRange (6) and bite (5). The Player and Health scripts are ready: the arrows push the player, and the player's Health has a public TakeDamage(int amount).
- While the player is closer than
guardRangeto the kennel, across the ground, the dog runs at the player. The range is measured from the kennel, not from the dog. - Otherwise the dog runs back to the kennel, and stands still once it is within 0.3 of it.
- The dog runs by setting its Rigidbody's velocity at
speedacross the ground, keeping its y velocity. - When the dog bumps into the player (tagged
Player), the player's Health takes 1 damage, and the player gets an Impulse ofbitestraight away from the dog, across the ground.
Press Play and walk up to 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
}
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall