- Home /
Only one bullet AI works?
I have an AI that moves towards the player and shoots, but for some reason when there are multiple enemies, the enemy itself does keep moving towards the player but the bullet only shoots out of the last enemy spawned. Am I doing something wrong? Here's the code:
public Rigidbody2D rb2d;
public Collider2D pc2d;
public float moveSpeed;
public float damage = 10f;
private void OnEnable()
{
StartCoroutine(Shoot());
Physics2D.IgnoreCollision(pc2d, FindObjectOfType<Enemy1Controller>().enemy1Collider);
}
IEnumerator Shoot()
{
Vector3 target = FindObjectOfType<PlayerController>().player.transform.position - transform.position;
rb2d.AddForce(target.normalized * moveSpeed * Time.deltaTime, ForceMode2D.Impulse);
rb2d.AddTorque(10000f, ForceMode2D.Impulse);
yield return new WaitForSeconds(2f);
Destroy(gameObject);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("Player"))
{
FindObjectOfType<PlayerController>().TakeDamage(damage);
}
Destroy(gameObject);
}
I believe what is happening here is that you're IgnoreCollision function is only finding the last spawned enemy, and not ignoring collisions for the enemies firing it. I usually have an initialization function in my projectiles and pass the attacker to the projectile for relevant functions like this.
Also.... you're scaling your bullets speed by Time.deltaTime, in a coroutine, which makes no sense because the coroutine doesn't run on the update thread, so it's actually only firing that function once and scaling it by delta time once. A bullet should have its own script to handle velocity, or you should create a bullet manager that manages the velocity of all instantiated bullets as well as object pools them to save on resources.
Thanks Rob, yeah that's correct, I changed the collider to trigger and the bullet does fire. I tried removing Time.delaTime but the bullets do move a lot faster. Does that mean I just need to decrease moveSpeed and it will be fine or do I need to do something else? I'm fairly new to Unity, so I'm not sure what you mean by "initialization function" and velocity scripts and things like that.
Your answer
Follow this Question
Related Questions
Shooting style like enter the dungeon 0 Answers
Transform.translate bullets problem 0 Answers
AI reflect shooting 0 Answers