- Home /
Crosshair and Ray
Hello, I'm having a problem with my crosshair behaviour.
This is the setup: I have a spaceship (handled with physics) and a camera following the spaceship in a smooth way (so it's following with a slight delay).
Since the spaceship slightly "moves" on screen (as I said, the camera is following smoothly) as the user turns and moves up/down, the crosshair can't be stuck in the middle of the screen but it has to follow the forward direction of the spaceship.
This is my code:
void FixedUpdate()
{
Ray ray = new Ray(player.position, player.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, rayDistance))
{
if (hit.collider)
{
this.transform.position = cam.WorldToScreenPoint(hit.point);
}
else
{
endPoint = ray.GetPoint(rayDistance);
this.transform.position = cam.WorldToScreenPoint(endPoint);
}
}
}
The part in the if statement (when the ray hits a collider) works perfectly fine: the else part, when the ray doesn't hit anything, simply doesn't work. I expected to make the crosshair follow the "end point" of the ray (rayDistance), but it doesn't move. It stays stuck in its last position.
What am I doing wrong? The code (and logic) behind that should be almost the same as the hit case, with the only difference that the crosshair follows the "end point" instead of the "hit point".
Thank you in advance.
Answer by BobyStar · Sep 06, 2021 at 12:54 AM
When you are using if (Physics.Raycast())
it will only run what is inside if the raycast hits something. You may want to move your else statement at the end of the Raycast check like so:
void FixedUpdate()
{
Ray ray = new Ray(player.position, player.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, rayDistance))
{
if (hit.collider)
{
this.transform.position = cam.WorldToScreenPoint(hit.point);
}
}
else // if the raycast does not hit anything
{
endPoint = ray.GetPoint(rayDistance);
this.transform.position = cam.WorldToScreenPoint(endPoint);
}
}
Your answer
Follow this Question
Related Questions
Changing position of a RayCast 1 Answer
What's wrong with my RaycastHit2D? 1 Answer
Physics.Raycast intermittently stops working 1 Answer
3rd person 3D aiming 1 Answer
I don't get Raycasts 0 Answers