CTIN 289 - Interactive Snippets Library

Powered by 🌱Roam Garden

Raycasting

Raycasting is great for AI. Checking if enemies are in your line of sight, and checking if the player is in the line of sight of enemies.

Old Mario games can draw two rays, one of each of his feet. Even if only half of Mario is on solid ground, he won't fall down.

The mouse doesn't exist in the game world. It's just a position on a 2D screen. Do you convert the mouse's screen position into a world position. Then you send a ray forward into the game world to see what it hits.

You can't see raycasts, so it can be hard to know if you're doing it right. Gizmos can help draw the ray in the editor for debugging purposes.

RaycastHit2D hit2D = Physics2D.Raycast(startOfRay, direction, distance);

//startOfRay = where to start the ray (Vector3)
//direction = which direction it goes (Vector3)
//distance = how far the ray should go (float)

// get the GameObject that the ray hit
GameObject otherGo = hit2D.collider.gameObject;
otherGo.GetComponent<SpriteRenderer>();
otherGo.gameObject.tag;
otherGo.SetActive(false);

// to find out if the ray hit something
if (hit2D.collider != null)
{
  print(hit2D.collider.name);
}

A raycast returns a RayCastHit2D which is a package of information about what happened with the raycast. A RayCastHit2D is very similar to a Collision object. It's not the thing that the ray collided with; it's a whole bunch of info that includes that.

A RayCastHit2D will never be null. You can't use a null check on a raycast, because the code will never be null whether or not the raycast actually hit something.

By default, the raycast will hit the same GameObject that is casting the ray. You can fix this in a couple of different ways

By starting the ray outside of the GameObject's collider

Or by setting up a layer mask