I am working on a game in Unity and my code for the Ranged Enemy’s Agro isn’t working. The script is for an enemy which shoots projectiles from a bow. If the enemy is close enough to the player it will shoot or walk towards the player until it is close enough to shoot. However, it will not move closer to the player when it is too far to shoot. All print statements are shown in the console. I have assigned all variables for the code yet the Enemy is still not chasing the player when he isn’t nearby.
Code in C#:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RangedAgro : MonoBehaviour
{
public float distanceToShoot;
public float distance;
private Transform player;
public Rigidbody2D rb;
public int speed;
public GameObject bullet;
public Transform bulletPos;
private float timer;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
distance = Vector2.Distance(transform.position, player.position);
if (distance <= distanceToShoot)
{
rb.velocity = Vector2.zero;
if(timer > 2){
timer = 0;
Shoot();
}
}
else if(distance > distanceToShoot)
{
Chase();
print("TRUE");
}
if(player.transform.position.x > transform.position.x) transform.eulerAngles = new Vector3(0, 0, 0);
if(player.transform.position.x < transform.position.x) transform.eulerAngles = new Vector3(0, 180, 0);
}
void Shoot()
{
Instantiate(bullet, bulletPos.position, Quaternion.identity);
}
void Chase()
{
if (player.position.x > transform.position.x)
{
rb.velocity = new Vector2(speed, 0);
transform.eulerAngles = new Vector3(0, 0, 0);
print("YES");
}else if (player.position.x < transform.position.x)
{
rb.velocity = new Vector2(-speed, 0);
transform.eulerAngles = new Vector3(0, 180, 0);
print("NO");
}
}
}
I tried making the else statement more specific by adding distance > distanceToShoot and also added some debugging by adding print statements.
TurtleLover69 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.