Clamp Ray to screen

Hi, I would like to have my endpoint within the borders of my screen.
Any Idea how to achieve that?

I am sending out a ray to define a point on that ray ( 150 unity3d units).
The only thing I could come up with would be a for loop that checks if the point is still in screen borders and if not, redo the calculation but reduce the lenght (150) by - 1 - so a recursive function. That sounds expensive since I am resetting the point in every frame…

var r = new Ray(sourceVector, direction);
var newEndPoint = r.GetPoint (150);

which direction are you sending that ray? you can use the cameras frustum agne and the angle of the vector to determine if its in the screen. just a reminder, Feild of View is the VERTICAL angle, to get the horizontal multiply it by the quotient of your aspect ratio.

1 Answer

1

It seems like there should be a simple way to do this, but the only thing I could think of was to use the planes of the camera frustum and use a Plane.Raycast(). Here is a bit of code as an example. Put this code on an object. Edit rayStart and rayDirection in the inspector. Note you have to do the GeometryUntility.CalculateFrustrumPlanes() calculation any time the position or rotation of the camera changes:

#pragma strict

var rayStart : Vector3 = Vector3.zero;
var rayDirection : Vector3 = Vector3.right;
var dist : float = 150;

private var planes : Plane[];
 
function Start() {
	planes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
}

function Update() {
	
	var ray = new Ray(rayStart, rayDirection);
	var pos = ray.GetPoint(dist);
	Debug.DrawRay(rayStart, rayDirection * dist);
	var d = dist;
	
	var enter : float;
	for (var plane : Plane in planes) {
		if (plane.Raycast(ray, enter)) {
			if (enter < d) {
				d = enter;
				pos = ray.GetPoint(enter);
			}	
		}
	}
	transform.position = pos;
}