Advertisement
branki922

CollisionDirections2D

Nov 16th, 2014
703
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.58 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. // But in unity you cant mix 2D and 3D so if you want to mix it than rays are your best bet
  5.  
  6. [RequireComponent(typeof(Rigidbody2D))]
  7. public class CollisionDirections : MonoBehaviour {
  8.  
  9.     public bool right=false, left=false, up=true, down=false;
  10.  
  11.     // Use this for initialization
  12.     void Start () {
  13.    
  14.     }
  15.    
  16.     // Update is called once per frame
  17.     void Update () {
  18.    
  19.     }
  20.  
  21.     void OnCollisionEnter2D(Collision2D coll){
  22.         //for every collision coll saves 2 points of contact test begining of collision and end of collision
  23.         if(coll.contacts.Length==2){
  24.             //chack are two points on x axis the same
  25.             if( coll.contacts[0].point.x == coll.contacts[1].point.x ){  
  26.                 // chack where they are in regards to game object origin
  27.                 if( coll.contacts[0].point.x > transform.position.x ){
  28.                     right=true;
  29.                 }else{
  30.                     left=true;
  31.                 }
  32.             }else if(coll.contacts[0].point.y == coll.contacts[1].point.y){
  33.                 if(coll.contacts[0].point.y > transform.position.y){
  34.                     up=true;
  35.                 }else{
  36.                     down=true;
  37.                 }
  38.             }
  39.         }else{
  40.             Debug.LogError("This script is defined only for 2D collisions");
  41.         }
  42.     }
  43.  
  44.     void OnCollisionExit2D(Collision2D coll){
  45.         if(coll.contacts.Length==2){
  46.             if( coll.contacts[0].point.x == coll.contacts[1].point.x ){
  47.                 if( coll.contacts[0].point.x > transform.position.x ){
  48.                     right=false;
  49.                 }else{
  50.                     left=false;
  51.                 }
  52.             }else if(coll.contacts[0].point.y == coll.contacts[1].point.y){
  53.                 if(coll.contacts[0].point.y > transform.position.y){
  54.                     up=false;
  55.                 }else{
  56.                     down=false;
  57.                 }
  58.             }
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement