I’m trying to make the enemy in my game (Simple 2d top-down game) shoot at the player, but so far nothing I’ve tried has worked.
I want the Enemy to shoot with a fire rate of 2 seconds and to only shoot if the player is 10m away(Yes, I realize I don’t have any code about the distance but I haven’t found anything that says about it so…).
Any help would be appreciated.
Here is my script for the Enemy shooting:
public class EnemyFire : MonoBehaviour
{
float fireRate;
float nextFire;
public Transform FirePoint;
public GameObject bulletPrefab;
public float bulletForce = 20f;
// Start is called before the first frame update
void Start()
{
fireRate = 3f;
nextFire = Time.fixedDeltaTime;
}
// Update is called once per frame
void Update()
{
CheckIfTimeToFire();
}
void CheckIfTimeToFire()
{
if(Time.fixedDeltaTime > nextFire)
{
GameObject Bullet = Instantiate(bulletPrefab, FirePoint.position, FirePoint.rotation);
Rigidbody2D rb = Bullet.GetComponent<Rigidbody2D>();
rb.AddForce(FirePoint.up * bulletForce, ForceMode2D.Impulse);
nextFire = Time.fixedDeltaTime + fireRate;
}
}
}
I also have this script set up for the Player shooting, if it helps:
public class Shooting : MonoBehaviour
{
public Transform FirePoint;
public GameObject bulletPrefab;
public float bulletForce = 20f;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, FirePoint.position, FirePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(FirePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
Also, i think will be good like this(I'm new at learning Unity, so idk if it will work how i think): //Check the distance between player and enemy If(Vector2.Distance(Player.transform.position,transform.position) <=10) bool canShoot = true; else bool canShoot == false; if(time.fixedDeltatime >= nextTimeTofire && canShoot == true) Shoot(); }
– Alex_SSS