- Home /
Raycast at angles
Hi All,
I am currently working on a simple line of sight system where 3 raycasts are used, one to the middle of the target and two either side of the target which can be seen in the image below:
I am struggling with getting the two raycasts to go either side of the targets position, currently I am using the following line of code:
var offsetRight = Quaternion.Euler(0, 1, 0) * rayDir;
var offsetLeft = Quaternion.Euler(0, -1, 0) * rayDir;
rayDir being the direction towards the target.
I know i need to replace the "1" with the angle from next to the target from the npc, could anyone explain how to do this? I know the answer is probably simple but I am drawing blanks on it.
Thanks for the assistance!
Answer by AlwaysSunny · May 03, 2015 at 09:13 PM
The easy way involves vector math instead of quaternions. It also implies you don't need angles greater than roughly 180 degrees, and that you don't need an exact angle measured in angles. You'll find the angles experimentally by changing N:
(To match your drawing almost perfectly, N would be one red dot's radius)
Use Vector3.Cross to get a vector perpendicular to your original raycast. The end points of your two "cone" rays will be at
right_ray_endpoint = center_ray_endpoint + cross_result.normalized * N;
left_ray_endpoint = center_ray_endpoint + cross_result.normalized * -N;
Hey Thanks for the assistance!
Your solutions seems to work and my 2 end points are consistently the correct spacing apart no matter what my distance, However my cone rotates vertically(sometimes the two points are the characters head and feet ins$$anonymous$$d of being next to the character) depending on the angle I move around the NPC, here is my following code:
Vector3 rayDir = (target.transform.position -_npc.transform.position).normalized;
float distance = Vector3.Distance(_npc.transform.position, target.transform.position);
Vector3 crossResult = Vector3.Cross(_npc.transform.position, (rayDir * distance));
var rightRayEndpoint = (rayDir * distance) + crossResult.normalized * 0.5f;
var leftRayEndpoint = (rayDir * distance) + crossResult.normalized * -0.5f;
Any assistance in where im going wrong will be appreciated!
Your answer
Follow this Question
Related Questions
user input azimuth and elevation angle. Need Urgent Help 0 Answers
Angle of bones to read the same as the inspector. 2 Answers
Aligning/mapping angles of Input.GetAxis(with .localEulerAngles 0 Answers
How to find direction Vector for a collision surface? 1 Answer
Rotate a gameobject by a specific angle and stop when character doesnt move anymore 0 Answers