ScreenPointToRay Not Aligning

Hi,
I have a character using the FirstPersonCharacterController script provided in standard assets. I would like to cast a ray from the center of the camera in the direction that the camera is facing. I thought ScreenPointToRay would be best. I was getting odd results so I39221-rayhelp.jpg debugged it with…

Ray debugRay = playerCamera.ScreenPointToRay(new Vector3(100,100,0));

Debug.DrawRay(debugRay.origin,debugRay.direction*50000000000,Color.red);

However the ray cast not casting straight I have attached a picture.

@MileSplit, Just use this line Debug.DrawRay(transform.position, transform.forward, Color.red); And attached this script to camera from where you want to cast a ray or use this line Debug.DrawRay(Camera.main.transform.position,Camera.main.transform.forward, Color.red); and you can use this for cast ray from main camera from any script

–

1 Answer

1

What makes you think you are casting a ray from the center of the screen with the code you have?

As the documentation say about ScrrenPointToRay the function takes a vector with the pixel coordinates of the screen to cast the ray from. You are supplying the coordinates Vectors3(100, 100, 0) which means that you shoot your ray from X coordinate 100 and Y coordinate 100. This would only be the middle of the screen if your entire screen is 200 width and 200 height, which I doubt it is very much. To shoot a ray from the middle of the screen you have to supply the function with coordinates for the middle of the screen which you can easily get by using the Screen class:

Vector3 centerOfScreen = new Vector3(Screen.width / 2, Screen.height / 2, 0);