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.