- Home /
Physics.Raycast issue | Ray not casting at certain angles?
So i am creating a camera orbit script right now and want to detect if anything is between the player and the camera.
For some reason, the ray is only getting cast when the camera is in front of the player and not behind him at an angle.
Here is my code along with some screenshots to the issue:
IN FRONT OF THE PLAYER
BEHIND THE PLAYER
You can see that the debug line is not even being drawn at that angle for some reason.
RaycastHit hit;
Ray ray = new Ray(RaycastOrigin.transform.position, RaycastTarget.transform.position);
if (Physics.Raycast(ray, out hit))
{
RaycastObstacle = hit.transform.gameObject;
Debug.DrawLine(RaycastOrigin.transform.position, RaycastTarget.transform.position, Color.red);
value = RaycastObstacle;
}
Answer by JedBeryll · Jan 12, 2016 at 11:30 PM
Common mistake: a raycast takes a starting point and a direction not an ending point. Either use LineCast which takes ending point instead, or calculate direction:
Vectror3 rayDirection = RaycastTarget.transform.position - RaycastOrigin.transform.position;
Ray ray = new Ray(RaycastOrigin.transform.position, rayDirection);
I looked into linecast but didnt know if it was the same as raycast since raycast can get "hit.transform.gameobject", which is what i need.
How would i get that infor using linecast? Or how would i be able to just get a "direction" that can point to my target using raycast?
"Or how would i be able to just get a "direction" that can point to my target using raycast?" I did just write that:
Vectror3 rayDirection = RaycastTarget.transform.position - RaycastOrigin.transform.position;
Ray ray = new Ray(RaycastOrigin.transform.position, rayDirection);
"How would i get that infor using linecast?" : The same way. public static bool Linecast(Vector3 start, Vector3 end, out RaycastHit hitInfo, int layer$$anonymous$$ask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
RaycastHit hit;
Physics.Linecast(RaycastOrigin.transform.position, RaycastTarget.transform.position, out hit);
Thank you for your response! Helped me learn more about raycasts and linecasts.
Your answer

Follow this Question
Related Questions
Raycasting will not hit some imported meshes with mesh colliders? 2 Answers
RaycastHit if/else Problem (bug?) 0 Answers
Raycast problem 1 Answer