- Home /
Raycast not rotating with object it casts from
I'm trying to build a generic aiming script for weapons, binoculars, and anything else that you would want to point in a specific direction. To accomplish this I'm casting a single ray in the direction I want bullets/eyes to go, and to ensure it fires from the center of the screen (where my crosshairs are at), I fire the ray from the main camera, as follows:
public LayerMask playerMask;
RaycastHit hit;
void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
Physics.Raycast(ray, out hit, 10f, playerMask);
}
void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, hit.point);
}
The problem I'm having is that when the player rotates around, the ray doesn't rotate with it, but instead remains pointing in it's original direction. My assumption is that it's using world coordinates, not local coordinates, but I thought transform.forward always gave you that gameobject's local transform, so I'm not sure what I'm doing wrong.
This script is on the camera? You are not checking the rerun value of the Raycast(), so the 'hit' can become stale. That is, if as you turn around the ray fails to hit things, the hit used by 'DrawLine()' will still point to the previous hit. So as a test do:
if (!Physics.Raycast(ray, out hit, 10f, player$$anonymous$$ask)) {
hit.point = Vector3.zero;
}
So now you will know in your OnDrawGizmos() that if the line is heading towards the world origin, the Raycast() failed.
Let's see, it's on the main camera, let me test it...
So you're absolutely right, this works now... one thing I'm a bit confused about though, if the player's layer is set to the same layer as player$$anonymous$$ask, shouldn't the ray pass through them without producing a hit? When I watch in scene view the ray constantly ter$$anonymous$$ates when it hits the player
So now I feel silly, it works perfectly!! Thank you so much :)
Your answer
Follow this Question
Related Questions
Unassigned Reference Exception 4 Answers
Aim-Assist with raycast 1 Answer
Camera rotate to look at GameObject from Raycast 3 Answers
How do I stop Script from making multiple Cameras? 1 Answer
Raycast in camera 1 Answer