- Home /
Trying to make an enemy fire at the player
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);
}
}
Answer by VARUN88 · Oct 14, 2020 at 01:43 PM
Hi @SebastianTarrant You can use this for checking the distance
void Update() {
//Check the distance between player and enemy
If(Vector2.Distance(Player.transform.position,transform.position) <=10) bool canShoot = true;
if(time.fixedDeltatime >= nextTimeTofire && canShoot == true) Shoot(); }
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(); }
Your answer
![](https://koobas.hobune.stream/wayback/20220613013508im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I make a 2d bullet object move towards the players original position when it is spawned? 2 Answers
How to change the fire rate on my shooting script? 1 Answer
Shooting a bullet object toward the mouse position in a 2D. 1 Answer
Why will the bullets sometimes not show up in the game view when the player shoots? 0 Answers
How to get an enemy to go to a location and then return.,Hi, 1 Answer