- Home /
Raycast hitting objects to the left of my player
I'm trying to make my walls turn transparent when they are between my player and the camera, and I'm using Raycast to detect when this happens. My current issue is the wall to the left of my player (even with considerable space between the two) is being hit by the Raycast. It was working fine before, but I can't seem to figure out why my Raycast seems to be grabbing to the wall to the left. Any ideas what I'm overlooking?
I've drawn 3 lines: What my camera is aiming the Raycast at, what is actually being hit, and my camera's forward.
void LateUpdate()
{
RaycastHit hit;
Ray ray = GetComponent<Camera>().ScreenPointToRay(thePlayer.transform.position);
if (Physics.Raycast(ray, out hit))
{
Debug.DrawLine(Camera.main.transform.position, thePlayer.transform.position, Color.blue);
Debug.DrawLine(Camera.main.transform.position, hit.transform.position, Color.red);
Debug.DrawRay(Camera.main.transform.position, transform.forward, Color.green);
Transform objectHit = hit.transform;
Answer by slavo · Nov 28, 2016 at 11:28 AM
Hello
ScreenPointToRay will return Ray that going through screen point you provide as parameter. But you are providing player position that is in world space.
You need to convert Player position from world space to screen space to get correct ray.
You need to use https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html for this.
So your code will looks like
RaycastHit hit;
Vector3 playerScreenPos = GetComponent<Camera>.WorldToScreenPoint(thePlayer.transform.position);
Ray ray = GetComponent<Camera>().ScreenPointToRay(playerScreenPos );
Your answer
Follow this Question
Related Questions
Using raycast from camera to aim shots 1 Answer
RE: RaycastHit and camera through walls 0 Answers
Working with RayCast 1 Answer