Question by
nitro0198 · Jul 10, 2021 at 01:10 PM ·
instantiateattack
How to make the enemy fire a few bullets and make him stop for a few seconds to reload
Hi, I have a simple patrol script for enemies, they just patrol an area and when the player enters their range they start firing. The problem, however, is that they shoot bullets endlessly, what I would like to do is to fire only 3 bullets and then wait a few seconds, and then continue firing, how could I do?
I also leave attached the script I am using
{ public float walkSpeed; public float range;
public float timeBTWshots; float distToPlayer; public float bulletSpeed;
bool mustPatrol;
public Rigidbody2D rb;
private bool mustTurn, canShoot;
public Transform groundCheckpos;
public LayerMask groundLayer;
public Collider2D bodyCollider;
private Animator anim;
public Transform player;
public GameObject Bullet;
public Transform shootPos;
void Start()
{
mustPatrol = true;
canShoot = true;
anim = GetComponent<Animator>();
}
void Update()
{
if (mustPatrol)
{
Patrol();
anim.SetBool("runshoot", true);
}
distToPlayer = Vector2.Distance(transform.position, player.position);
if (distToPlayer <= range)
{
if (player.position.x > transform.position.x && transform.localScale.x < 0||player.position.x<transform.position.x && transform.localScale.x>0)
{
Flip();
}
mustPatrol = false;
if (mustPatrol == false)
{
anim.SetBool("runshoot", false);
rb.velocity = Vector2.zero;
anim.SetTrigger("shootenemy");
}
if(canShoot)
StartCoroutine(Shoot());
}
else
{
mustPatrol = true;
}
}
void FixedUpdate()
{
if (mustPatrol)
{
mustTurn = !Physics2D.OverlapCircle(groundCheckpos.position, 0.1f, groundLayer);
}
}
void Patrol()
{
if (mustTurn||bodyCollider.IsTouchingLayers(groundLayer))
{
Flip();
}
rb.velocity = new Vector2(walkSpeed * Time.fixedDeltaTime, rb.velocity.y);
}
void Flip()
{
mustPatrol = false;
transform.localScale = new Vector2(transform.localScale.x * -1, transform.localScale.y);
walkSpeed *= -1;
mustPatrol = true;
}
IEnumerator Shoot()
{
canShoot = false;
yield return new WaitForSeconds(timeBTWshots);
GameObject newBullet = Instantiate(Bullet, shootPos.position, Quaternion.identity);
newBullet.GetComponent<Rigidbody2D>().velocity = new Vector2(bulletSpeed * walkSpeed * Time.fixedDeltaTime, 0f);
canShoot = true;
}
}
Comment
Your answer