- Home /
Ensure a bullet only hits one enemy
Hello, I am making a 2D top down shooter game, and I am encountering a problem where a bullet would hit and deal damage to two or more enemies if it collides with both, even though it is supposed to only hit one enemy and destroy itself.
Here is the code for the bullet:
public class BulletMovement2 : MonoBehaviour
{
private float moveSpeed = 100f;
public float DestroyDelay = 0.05f;
private EnemyHealthManager enemyHealth;
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.right * moveSpeed * Time.deltaTime);
DestroyDelay -= Time.deltaTime;
if (DestroyDelay <= 0)
{
if (gameObject != null)
{
Destroy(this.gameObject);
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (gameObject != null && !collision.gameObject.CompareTag("Player")&& !collision.gameObject.CompareTag("Bullet"))
{
if (collision.gameObject.CompareTag("Enemy"))
{
enemyHealth = collision.gameObject.GetComponent<EnemyHealthManager>();
enemyHealth.reduceCurrentHealth(1);
}
Debug.Log("Collided with " + collision.gameObject.name);
Destroy(gameObject);
}
}
}
You are moving the object in Update using transform.Translate
. Thus, you are messing up with the physics engine.
You should be moving the object in FixedUpdate using the Rigidbody component.
This should limit the problem.
You can also add a flag (bool) you turn to true
in OnTriggerEnter2D
and check against this value to ensure you've inflicted damage only once.
Answer by HitarthPadaliya · Nov 06, 2020 at 12:03 PM
You can destroy the bullet gameobject right after you reduce enemy's health. Just add this line after line 30 :-
Destroy (gameObject);
Another option : you can add a bool "enemyHit" and check if it is false, right before you do everything and then after line 30, you can set it true.
First option doesn't work. It's pretty much the same as what I already have.
Second option with using a boolean worked.
Your answer
Follow this Question
Related Questions
Complex collision layers 1 Answer
Player passing through wall when pushed 2d C# 0 Answers
Detecting collision with OnCollisionEnter2D not working 1 Answer
2d Collision not detect player when it falls 2 Answers
2D Collider seems bigger than it is 1 Answer