The Hunters Bite
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 63 of 71.
Challenge
MediumMake the hunters bite and knock the player back.
- In
Hunter, add[SerializeField] private float knockback = 12f;andvoid OnCollisionEnter(Collision collision). - Inside, when
collision.gameObject.TryGetComponent(out Health health), callhealth.TakeDamage(1);. - Then push it:
awayfrom the hunter to the player, y set to 0, andcollision.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
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 WallPractice on your own: Unity playground