Setting exact Angle of a Raycast instead of using Direction

Hi everyone,

I am starting out using Raycasts but wanted to set a raycast that would check in a specific angle, instead of using the regular Vector3 directions like (Vector3.forward).

So something like:

float angleToCheck = 63f;
if( Physics.Raycast(transform.position, angleToCheck, out hit, 10f )

Obviously the above won't work as a Vector3 is required, but is there a way to represent the angle I am looking for as a vector3 that the raycast will accept? The angle needs to be relative to my gameobject, not the world.

For more background, this is a 2D game, so objects move along the X and Y axis not the Z (vector3.up or y-axis is the front of my objects).


You can just build a vector corresponding to the angle, e.g. (untested):

direction = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0f);

Depending on what convention you're using for your angles, you might need to swap and/or negate the first two arguments to the Vector3 constructor to get the right results.