Menu
CoddyTech

The Hunters Bite

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

challenge icon

Challenge

Medium

Make the hunters bite and knock the player back.

  1. In Hunter, add [SerializeField] private float knockback = 12f; and void OnCollisionEnter(Collision collision).
  2. Inside, when collision.gameObject.TryGetComponent(out Health health), call health.TakeDamage(1);.
  3. Then push it: away from the hunter to the player, y set to 0, and collision.rigidbody.AddForce(away.normalized * knockback, ForceMode.Impulse);.

Press Play and see how long you last. Then Check.

Try it yourself

using UnityEngine;

public class Hunter : MonoBehaviour
{
    [SerializeField] private float speed = 3f;
    private Rigidbody rb;
    private Transform player;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        player = GameObject.FindWithTag("Player").transform;
    }

    void FixedUpdate()
    {
        Vector3 toPlayer = player.position - rb.position;
        toPlayer.y = 0f;
        Vector3 dir = toPlayer.normalized;
        rb.linearVelocity = new Vector3(dir.x * speed, rb.linearVelocity.y, dir.z * speed);
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground