Using Camera ViewportPointToRay (Unity)

z4gon
z4gon

Raycasting from the Camera and finding the hit point in a plane, to determine a surface area corresponding to the proyected view from the Camera on the Plane.

References

Table of Content


Using Raycast

The method ViewportPointToRay transforms a coordinate in viewport space (0,0) to (1,1) into a ray that starts from the corresponding point in the camera near clip plane and points into the direction coming from the camera transform position.

Using a trigger collider for a plane, you can raycast this ray and find the hit point in the surface.

This allows to generate a shape that corresponds to the camera view, proyected on a surface, even when the camera is tilted.

1private Camera mainCamera; 2private LayerMask raycastLayerMask; 3private float raycastMaxDistance = 40; 4private Transform[] corners; 5 6void Awake() 7{ 8 PositionCorner(new Vector2(0.0f, 0.0f), corners[0]); 9 PositionCorner(new Vector2(1.0f, 1.0f), corners[1]); 10} 11 12private void PositionCorner(Vector2 viewportPoint, Transform corner) 13{ 14 RaycastHit hit; 15 var ray = mainCamera.ViewportPointToRay(points[i]); 16 if ( 17 Physics.Raycast( 18 ray, 19 out hit, 20 raycastMaxDistance, 21 raycastLayerMask, 22 QueryTriggerInteraction.Collide 23 ) 24 ) 25 { 26 corner.transform.position = hit.point; 27 } 28}

Picture


Drawing Gizmos

The gizmos are useful for visualizing the area shape.

1void OnDrawGizmos() 2{ 3 if (corners != null && corners.Length > 1) 4 { 5 var botLeft = corners[0].transform.position; 6 var botRight = new Vector3(-botLeft.x, botLeft.y, botLeft.z); 7 var topRight = corners[1].transform.position; 8 var topLeft = new Vector3(-topRight.x, topRight.y, topRight.z); 9 10 Gizmos.color = Color.yellow; 11 12 Gizmos.DrawLine(topLeft, topRight); 13 Gizmos.DrawLine(botLeft, botRight); 14 Gizmos.DrawLine(botLeft, topLeft); 15 Gizmos.DrawLine(botRight, topRight); 16 } 17}

Picture