Home > Blockchain >  Using 2D raycast in perspective not returning collision
Using 2D raycast in perspective not returning collision

Time:10-06

I'm using 2D colliers in my game, and I want to use a perspective camera also. I have a raycast working in orthographic that draws a line from the player to a clicked point. It, of course, breaks when I change the camera to perspective.

I've been trying to get it to work in 2D, but without success. I'm trying to cast a ray from the player character in the direction of the mouse position on screen, and returning the first hit 2D collider.

This is what I have so far which doesn't work. I appreciate some help.

void RaycastToCollider()
{
    Ray ray = new Ray();
    ray.direction = Camera.main.ScreenToViewportPoint(Input.mousePosition) - transform.position;
    ray.origin = transform.position;
    RaycastHit2D hit = Physics2D.GetRayIntersection(ray, Mathf.Infinity);
    if (hit.collider != null)
    {
        Debug.DrawLine(ray.origin, hit.point);
    }
}

CodePudding user response:

Why ScreenToViewportPoint? This only returns a pixel position (e.g. 356 x 847) into normalized viewport coordinates that move in range 0 to 1 (e.g. 0,07 * 0,26)

Since it is purely about the direction you want to get you could go the other way round via the screen.

Also not sure but I would simply use a Raycast instead of GetRayIntersection

void RaycastToCollider()
{
    // already is in screen space anyway
    var mouseScreenPos = Input.mousePosition;
    var transformPos = transform.position;
    var transformScreenPos = Camera.main.WorldToScreenPoint(transformPos);
    var direction = (Vector2)mouseScreenPos - (Vector2)transformScreenPos;
    var ray = new Ray(transformPos, direction);
    
    var hit = Physics2D.Raycast(transformPos, direction, Mathf.Infinity);
    
    if (hit.collider != null)
    {
        Debug.DrawLine(ray.origin, hit.point);
    }
}

enter image description here

  • Related