- Home /
Using raycast from camera to aim shots
I'm trying to make the player camera use a raycast that aims at the center of the screen. I'm trying to have one of my weapons aim at the raycast hit on its own so that, when I press the mouse button to shoot this weapon, it targets the raycast hit.
However, I've run into some problems. One of these problems involves the following line of C# code:
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
The issue stems from the "ScreenPointToRay" portion of the code. When I copied and pasted the code into MonoDevelop, this very part of the script displays in red. Is something wrong with the code? Is the documentation somehow incorrect?
Answer by KdRWaylander · May 27, 2015 at 07:50 AM
Hi,
If it's red it means that 'ScreenPointToRay' is not a member of 'camera'. Since your code seems to be good, the problem must come from 'camera'. Try replacing 'camera' by 'Camera.main' (which returns the camera tagged 'Main Camera') ? Is 'camera' the gameobject or the camera component ?
It's the camera itself. I don't think I've heard of the "camera component".
P.S.: what is "Camera.main"?
P.S.S.: the code below is what first brings up the player's camera in the script:
public Camera playerCamera;
Camera.main is a piece of code that will always return the camera with the "$$anonymous$$ain Camera" tag. It's like GameObject.Find("$$anonymous$$ain Camera") !
Alright so you do take the component, try changing the type to
public GameObject playerCamera;
If you are, in fact, declaring the Camera using
public Camera playerCamera;
and calling it using
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
then that's a big part of the problem right there.
"camera" is something you can jump to/between, like "gameObject" and "transform" (i.e. gameObject.transform.position). Your variable is "playerCamera" which means you're not actually calling it. Ins$$anonymous$$d, you're calling the camera component of the object the script is attached to, whether it has one or not.
Okay, but now this brings up another problem. As soon as I change "Camera" to "GameObject", the ".ScreenPointToRay" portion of the code turns red. Is there an alternative to this code piece?
Alright,
Try calling the camera with the type GameObject (`public GameObject playerCamera;`)
Then, in your ray, call the camera component of the object:
Ray ray = playerCamera.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
Your answer
![](https://koobas.hobune.stream/wayback/20220613200328im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Raycast hitting objects to the left of my player 1 Answer
Raycast in camera 1 Answer
Raycasting with Rotation of Camera 0 Answers