- Home /
Collision detection not working as intended
Hey all, newbie here I am trying to make a basic 2D platformer and getting help from a book named "Unity 2D game development" So I have a bullet prefab with box2D, and a collider for my enemy object. Using events and delegates for hit detection script(Know it's an overkill, just book stated so) Problem is, when I am shooting an enemy, it doesn't always kill him despite the simple Destroy(gameObject, 0.1f) command. Sometimes it hits and kills, but sometimes it doesn't(Bullet gets lost, so I guess collision is made) Any idea why?
using UnityEngine;
using System.Collections;
public class TakeDamageFromPlayerBullet : $$anonymous$$onoBehaviour
{
public delegate void hitByPlayerBullet();
public event hitByPlayerBullet hitByBullet;
void OnTriggerEnter2D( Collider2D collidedObject )
{
if(collidedObject.tag == "Player Bullet")
{
if(hitByBullet != null) hitByBullet();
}
}
}
public void hitByPlayerBullet()
{
GameObject deathFxParticle = (GameObject)Instantiate(deathFxParticlePrefab);
Vector3 enemyPos = transform.position;
Vector3 particlePos = new Vector3(enemyPos.x,enemyPos.y,enemyPos.z +1.0f);
deathFxParticle.transform.position = particlePos;
Destroy(gameObject,0.1f);
}
I think your bullet is too fast and small, so it isn't above the enemy collider.
Check if changing the collision detection to continuos works
Answer by Pyrian · Sep 04, 2014 at 01:28 PM
Probably the bullet is getting destroyed before the collision registers with the enemy. This is a common problem when making collisions that destroy both participants. Instead of destroying them in the event, simply set a Boolean flag, and destroy them in Update.
Thanks! Changed bullet's code to Destroy(gameObject,0.1f); and it helped