Simple collision detection in Unity 2D

Posted by N1ghtshade3 on Game Development See other posts from Game Development or by N1ghtshade3
Published on 2014-08-19T01:42:10Z Indexed on 2014/08/19 4:33 UTC
Read the original article Hit count: 285

Filed under:
|
|
|

I realise other posts exist with this topic yet none have gone into enough detail for me. I am attempting to create a 2D game in Unity using C# as my scripting language.

Basically I have two objects, player and bomb. Both were created simply by dragging the respective PNG to the stage.

I have set up touch controls to move player left and right; gravity of any kind is not needed as I only require it to move x units when I tap either the left or right side of the screen. This movement is stored in a script called playerController.cs and works just fine.

I also have a variable health = 3 for player, which is stored in healthScript.cs.

I am now at a point where I am stuck. I would like it so that when player collides with bomb, health decreases by one and the bomb object is destroyed. So what I tried doing is using a new script called playerPhysics.cs, I added the following:

void OnCollisionEnter2D(Collision2D coll){
        if(coll.gameObject.name=="bomb")
            GameObject.Destroy("bomb");
            healthScript.health -= 1;
}

While I'm fairly sure I don't know the proper way to reference a variable in another script and that's why the health didn't decrease when I collided, bomb never disappeared from the stage so I'm thinking there's also a problem with my collision.

Initially, I had simply attached playerPhysics.cs to player. After searching around though, it appeared as though player also needed a rigidBody attached to it, so I did that. Still no luck. I tried using a circleCollider (player is a circle), using a rigidBody2D, and using all manner of colliders on one and/or both of the objects. If you could please explain what colliders (if any) should be attached to which objects and whether I need to change my script(s), that would be much more helpful than pointing me to one of the generic documentation examples I've already read. Also, if it would be simple to fix the health thing not working that would be an added bonus but not exactly the focus of this question.

Bear in mind that this game is 2D; I'm not sure if that changes anything.

Thanks!

© Game Development or respective owner

Related posts about c#

Related posts about unity