Hi, I’m making a top down shooter game right now and I’m currently working on a ranged enemy. The enemy should shoot at the player, and it does, but the projectile fires at the player’s last position and stops when it gets there. I want it to continue past. I have 2 scripts here, one for the enemy itself and the other for the projectile:
{
public float speed;
public float stoppingDistance;
public float retreaDistance;
public float bulletForce = 20f;
private float timeBtwShots;
public float startTimeBtwShots;
public Transform player;
public Transform firePoint;
public GameObject projectile;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
timeBtwShots = startTimeBtwShots;
}
// Update is called once per frame
void Update()
{
Vector3 direction = player.position - transform.position;
direction.z = -100000;
transform.rotation = Quaternion.LookRotation(direction, Vector3.forward);
if (Vector2.Distance(transform.position, player.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
}
else if (Vector2.Distance(transform.position, player.position) < stoppingDistance && Vector2.Distance(transform.position, player.position) > retreaDistance)
{
transform.position = this.transform.position;
}
else if (Vector2.Distance(transform.position, player.position) > retreaDistance)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, -speed * Time.deltaTime);
}
if (timeBtwShots <= 0)
{
Shoot();
timeBtwShots = startTimeBtwShots;
}
else
{
timeBtwShots -= Time.deltaTime;
}
void Shoot()
{
GameObject bullet = Instantiate(projectile, firePoint.position, firePoint.rotation);
Rigidbody2D rb = projectile.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
And the projectile one:
{
public float speed;
public GameObject hitEffect;
private Transform player;
private Vector2 target;
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
target = new Vector2(player.position.x, player.position.y);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D collision)
{
GameObject effect = Instantiate(hitEffect, transform.position, Quaternion.identity);
Destroy(effect, 5f);
Destroy(gameObject);
}
}