How To Send a Raycast Out at an Angle

I have the code below. I am trying to send out a raycast from the camera’s position forward but at some angle vertically. Basically I would like the raycast to be sent out at 12 off center of the screen. The code below doesn’t seem to be working. Any help would be greatly appreciated!

``````float angle = 12;
Ray ray = new Ray();
ray.origin = mainCameraT.position;
ray.direction = new Vector3(Mathf.Cos(angle), Mathf.Sin(-angle), 0f);
RaycastHit raycastHit = new RaycastHit();
if( Physics.Raycast( ray, out raycastHit, 300) ){
return raycastHit.point;
}
return mainCameraT.position + mainCameraT.forward * 100;
``````

Thanks

Mathf.Sin and Cos take an angle in radians as input, rather than degrees. Mathf luckily does have a function that will allow you to convert the two.

There’s also a way easier way to do this. You can multiple Quaternions by Vectors and the product will be the rotation of the Vector. This achieves the same thing that yours would, once it’s converted to radians.

``````ray.direction = Quaternion.AngleAxis(12.0f, Vector3.forward) * Vector3.right;
``````

Erik