Advertisement
Jellybit

AABB collision for Unity3D

Dec 27th, 2013
2,247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public static class Aabb
  5.  
  6. {
  7.    
  8.     public static bool Colliding( GameObject a, GameObject b )
  9.     {
  10.         Rect aBox = a.BoxToRect();
  11.         Rect bBox = b.BoxToRect();
  12.  
  13.         // Find out if these guys intersect
  14.         return Intersect ( aBox, bBox );
  15.     }
  16.  
  17.     // This checks the intersection between two rectangles.
  18.     public static bool Intersect( Rect a, Rect b )
  19.     {
  20.         // Basic AABB collision detection. All of these must be true for there to be a collision.
  21.         bool comp1 = a.yMin > b.yMax;
  22.         bool comp2 = a.yMax < b.yMin;
  23.         bool comp3 = a.xMin < b.xMax;
  24.         bool comp4 = a.xMax > b.xMin;
  25.        
  26.         // This will only return true if all are true.
  27.         return comp1 && comp2 && comp3 && comp4;
  28.     }
  29.  
  30.     // This converts a BoxCollider2D to a rectangle for use in determining an intersection
  31.     private static Rect BoxToRect ( this GameObject a )
  32.     {
  33.         // Finding the BoxCollider2D for the GameObject.
  34.         BoxCollider2D aCollider = a.GetComponent<BoxCollider2D> ();
  35.  
  36.         // Grabbing the GameObject position, converting it to Vector2.
  37.         Vector2 aPos = a.transform.position.V2();
  38.        
  39.         // Now that we have the object's worldspace location, we offset that to the BoxCollider's center
  40.         aPos += aCollider.center;
  41.         // From the center, we find the top/left corner by cutting the total height/width in half and
  42.         // offset by that much
  43.         aPos.x -= aCollider.size.x/2;
  44.         aPos.y += aCollider.size.y/2;
  45.        
  46.         // Create a rectangle based on the top/left corner, and extending the rectangle
  47.         // to the width/height
  48.         return new Rect ( aPos.x, aPos.y, aCollider.size.x, -aCollider.size.y );
  49.     }
  50.  
  51.     // Converts a Vector 3 to Vector 2
  52.     private static Vector2 V2 ( this Vector3 v )
  53.     {
  54.         // Converts the Vector3 to a Vector2.
  55.         return new Vector2 (v.x, v.y);
  56.     }
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement