Menu
CoddyTech

Recap: Guard Dog

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 55 of 63.

challenge icon

Challenge

Medium

A 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 guardRange to 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 speed across 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 of bite straight 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