Answer the question
In order to leave comments, you need to log in
How to handle bullet collision with objects in Unity2D?
Good afternoon. I have a problem when I shoot and there are a lot of enemies coming and their colliders intersect, then the bullet does damage to several enemies. How to make a bullet only deal damage to one enemy? I do the check through OnTriggerEnter2D.
Example:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == enemyName)
{
Destroy();
DamageEnemy(collision.transform);
}
}
void DamageEnemy(Transform enemy)
{
Enemy e = enemy.GetComponent();
if (e != null)
{
e.TakeDamage(damage);
}
}
Answer the question
In order to leave comments, you need to log in
Solved the Problem, here is my code:
void Update()
{
transform.Translate(Vector2.right * Time.deltaTime * speed);
DamageObject();
}
void DamageObject()
{
Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPosition = new Vector2(Gun.gun.firePoint.position.x, Gun.gun.firePoint.position.y);
RaycastHit2D raycastHit2D = Physics2D.Raycast(firePointPosition, mousePosition - firePointPosition, 100, toHit);
Vector2 dir = raycastHit2D.point - (Vector2)transform.position;
float dist = speed * Time.deltaTime;
if (rangeRadius > 0)
{
Collider2D[] collider2D = Physics2D.OverlapCircleAll(transform.position, rangeRadius);
foreach (Collider2D col in collider2D)
{
if (col.tag == enemyName)
{
DamageEnemy(col.transform);
Destroy(gameObject);
}
}
}
else if (dir.magnitude <= dist)
{
if (raycastHit2D.collider != null)
{
Enemy enemy = raycastHit2D.collider.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
Destroy(gameObject);
}
}
}
}
void DamageEnemy(Transform enemy)
{
Enemy e = enemy.GetComponent<Enemy>();
if (e != null)
{
e.TakeDamage(damage);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question