2D Raycasting in Unity 4.3

Tags: Unity3d, 4.3, 2D, ray, raycasting, collision detection

Unity 4.3 released today and I was super excited for the brand new 2D tools that came with it. I very quickly dug in and began playing with the built in physics, which while work, produce results that I particularly wasn't fond of. Being a programmer with some understanding of how these things might work, I figured it would be easier to roll my own collision detection using raycasting rather than fight the system provided to me. There are lots of examples out there on how to do raycasting with the 3D components of Unity but I just couldn't get those examples to work using the 2D colliders. As it turns out there were new physics objects to work with and once I got it all figured out it worked great. I've written this post in order to help others learning the ropes with the Unity 2D tools in case someone else runs into the same issues I did. 

 

To start off with, there are some key objects, methods, and properties that I worked with and I'd like to explain those individually now:

  • Physics2D - this is where you will find static classes and methods to work with your 2D objects
  • Physics2D.Raycast() - this is specifically the method we are going to work with to accomplish our 2D raycasting. This method returns a RaycastHit2D object, but otherwise behaves much like the traditional Physics.Raycast
  • RaycastHit2D - this class contains all sorts of information about the results of our raycast
  • RaycastHit2D.fraction - this property gives us the the distance between the origin of our ray and the hit target
  • RaycastHit2D.collider - this property gives us an instance of the collider that was hit by the raycast

 

To put all this together into something usable is quite easy once you know what you are doing.

 

// The starting point of the ray to be cast 
// Could be the edge of an object for collision detection
Vector2 origin;

// The direction that the ray should be cast towards 
// Following suit of the example above this could be the direction a collidable object is moving
Vector2 direction;

// This is reactionary data 
// We will use this to determine if we are close enough to an object perform some action
Vector2 speed;

void CheckCollision()
{
	//Performs the raycast from the origin value towards the direction specified; returns hit data about the cast
	RaycastHit2D hitInfo = Physics2D.Raycast(origin, direction);

	//If we are going to run into this object at our current speed lets do something
	if (hitInfo.fraction < speed)
	{
		//do stuff
	}
}

 

Hopefully the comments (and the code) are pretty self explanatory given the explanation of objects, methods, and properties provided above. If you do have any questions or feedback, feel free to leave a comment below. 

  

Comments powered by Disqus