2D Collision (Shooting projectiles)

Hey guys,

I’m making a 2D platformer where you can shoot a projectile at an enemy. Problem is I can’t get the “OnTriggerEnter2D” to work right. I currently have it set up where my Player shoots the prefab (bullet) which has a box collider and rigibody on it but when it hits the enemy (also has a box collider and rigibody) it doesn’t display my Debug Log statement. If i check “Is Trigger” on the enemy (underneath Box Collider) it does show the debug statement when the enemy is hit but then my enemy falls through the platforms. I’ve been researching this like crazy and I can’t seem to find any solution.

I know this is because I’m using gravity and is trigger ignores collisions. I also tried setting a tag on the enemy and having an IF statement in the Ontriggerenter2D function but it has the same results. I think it has something to do with how I’m using it in the inspector and the collision just simply isn’t being detected. All the Box colliders are the correct sizes and touching each other.

Is there away to use OnTriggerEnter2D and still use gravity?

Thanks for your help and please excuse my new-ness.
Enemy:

Projectile:

Gravity is effectively a force that moves a dynamic body, it has nothing to do with collision-detection whatsoever.

It sounds like you’re expecting an “OnTriggerEnter2D” callback when the collider isn’t a trigger? In that case you get an “OnCollisionEnter2D” callback. Is this your issue?

1 Like

Thanks for the reply.
So last night I tried using this but when I used this the bullet wouldn’t project at all. I realized this morning that its because the “fire point” was colliding with the character box collider and immediately destroying itself.

My only question now is that it doesn’t alllow me to use the .name definition on my Collision. I’m guessing its because OnCollisionEnter2D uses collision and not collider in the parameter?

Nevermind! I found it on another unity answer. You have to access the collider component:

 Debug.Log("collided with " + hitInfo.collider.gameObject.name);

Here is the link that worked for me:
https://answers.unity.com/questions/431697/checking-for-a-name-on-collision.html

It’s in the docs but you can access Collision2D.gameObject.

1 Like

If you add a OnCollisionEnter2d to you bullet script. Use tags better instead of object name

Example:

void OnCollisionEnter2D (Collision2D col) {
        if (col.gameObject.compareTag ("Enemy"){
                destroy (gameObject);
                destroy (col.gameObject);
         }
}

This is for prevent any changes in object name.

Please Sir can u show me how u fix the firepoint was colliding with the character box collider