Shoot
Lesson 9 of 25 in Coddy's Unity Game: Tower Defense course.
A tower fires a Projectile at its target. The shot flies there with MoveTowards, following the target as it walks, and hurts it on arrival. It does not need to know it hit an Enemy: it asks for IDamageable, the interface for anything that can take damage, so anything that implements it can be shot.
A target can die while a shot is in the air. A destroyed Unity object compares equal to null, so the shot checks target == null first and destroys itself.
For now a tower fires once a second. It keeps the time of its next shot:
if (Time.time >= nextShot)
{
Fire();
nextShot = Time.time + 1f;
}Challenge
MediumTowers shoot arrows, once a second.
EnemyimplementsIDamageable:TakeDamage(int amount)takes it offhealth, destroying the enemy at 0 or less.Projectile:Launch(Transform target, int damage)keeps both;Updateflies to the target atspeed, callsTakeDamage(damage)on arrival and destroys itself, also when the target is gone.Tower: addpublic int damage = 2;and[SerializeField] private Projectile projectilePrefab;; fire as above fromtransform.position + Vector3.up.
Press Play: arrows fly and Grunts fall. Then Check.
Try it yourself
using UnityEngine;
// Comes later: a shot that flies from a tower to its target.
public class Projectile : MonoBehaviour
{
}
All lessons in Unity Game: Tower Defense
Practice on your own: Unity playground