- Home /
 
2D Collision
Hi!
I'm making a 2D game where you are a space ship dodging asteroids. The asteroids and space ship are just rectangles at the moment so i use BoxCollider2D for both of them. I tag the astroid as "Asteroid" and the player space ship as "Player". I then make 2 scripts. The problem is that nothing happens when the two objects are supposed to collide.
PlayerCollision:
 function Start () {
 }
 
 function Update () {
 
 }
 
 function OnCollisionEnter2D(coll: Collision2D){
    if(coll.gameObject.tag=="Asteroid"){
       Destroy(gameObject);
    }
 }
 
               AsteroidCollision:
 function Start () {
 
 }
 
 function Update () {
 
 }
 
 function OnCollisionEnter2D(coll: Collision2D){
    if(coll.gameObject.tag=="Player"){
       Application.LoadLevel(Application.loadedLevel);
       Destroy(gameObject);
    }
 
              Answer by GimLee · Aug 17, 2014 at 02:43 AM
Seems weird. I know this script of mine works, it's in C# though. But feel free to test it.
 void OnCollisionEnter2D(Collision2D coll) 
     {
         if (coll.gameObject.tag == "Player")
         {
 
                 player.Die();
 
         }
         
     }
 
               Also, I wouldn't have an OnCollisionEnter on both my scripts. Keep it at one of them. But I might be wrong.
If you want it in only one script do like this on your AsteroidCollision:
 private PlayerCollision player; //Or whatever scriptname u have
 
 
 
 void OnCollisionEnter2D(Collision2D coll) 
     {
         if (coll.gameObject.tag == "Player")
         {
                 player.Die();
         }
 
     }
 
 void Start () {
     player = GameObject.Find("playerObjectName").GetComponent<PlayerCollision>();
     }
 
              Your answer
 
             Follow this Question
Related Questions
Collision isn't detected between two obects 1 Answer
Different results between "ContactPoint" and "ContactPoint2D" 0 Answers
Having problems with 2d collision triggers (javascript) 1 Answer
Collision with renderer.enabled? 0 Answers
How can I make a non-player character (rigidbody) move when they touch the ground? 1 Answer