How to make a Ray Cast

So I’ve started a new Game Project and I’m trying to make a ray cast that can collide with other game objects but for some reason it isn’t working not only is it giving zero collision back but it also isn’t appearing on the game screen does anyone know way. This is the code.

public Camera main;

Vector2 mousePos = new Vector2();
Vector3 point = new Vector3();

RaycastHit2D hit;

void Update()
{
    mousePos = Input.mousePosition;
    point = main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10));
    hit = Physics2D.Raycast(transform.position, point);
    Debug.Log(point);
    Debug.Log(hit.collider);
    Debug.DrawRay(transform.position, point);
}

That’s because both Raycast and DrawRay take a direction as their second parameter, not a point: Unity - Scripting API: Physics2D.Raycast

If you want the direction toward a specific point, you need to subtract the starting point (transform.position) from the point. If you want the ray to stop at the point, you must also provide the distance parameter. To do this, normalize the difference vector to get the direction, then calculate the distance as the magnitude of the difference.

As Meredoth points out you’re misusing the API, but don’t worry, it’s an easy API to mis-use.

Here’s how to use Raycast… I always do this:

Always use named arguments with Physics.Raycast() because it contains many poorly-designed overloads:

In addition to the above, if you want to specify two world positions, use Physics2D.Linecast. For drawing you’d then use Debug.DrawLine.

I would definitely recommend looking carefully at the scripting docs when having an issue before you spend time writing up a question. :slight_smile:

@MelvMay, is there any practical differences between Physics2D.Raycast(from, (to - from).normalized, (to - from).magnitude) and Phyiscs2D.LineCast(from, to), or is it just a convenience function?

Also, uh, the Linecast documentation says:
“Note that this function will allocate memory for the returned RaycastHit2D object.”
but RaycastHit2D is a struct! Is this talking about some c++ engine-side allocation, or is it just plain wrong?

That line was removed from a lot of pages a long time ago, seems like this one was missed. It’s wrong for the reason you stated. I’ll get it changed.

They are equivalent. Box2D doesn’t have a raycast using direction/distance even though its internal function is named as such. It has a (pointA, pointB) so linecast fits exactly but raycast has to calculate pointB from pointA + (direction * distance). If you use an “infinite” distance, we use an arbitrarily crazy large distance well beyond anything that Unity really supports. The direction is always normalized.

Right, so that means that any normalization we do on our side is wasted work. Good to know!

I mean the direction is always used normalized. There’s a fast normalized check so it’s not wasted. If you do it, we don’t need to. I doubt it matters much in the scheme of things though.