How to make my "ray" always hit center of the screen?

Hey guys. I’ve got an issue. I don’t know how to fix this.

So I want my _laserPrefab to always hit the middle of the screen, but for now, it looks like this:
For far object’s it’s almost in the center


But for the close ones it looks terrible:


My code:

RaycastHit hit;
            if (Physics.Raycast(_camera.transform.position, _camera.transform.forward, out hit, range))
            {
                TargetController target = hit.transform.GetComponent<TargetController>();
  
                if (target != null)
                {
                    target.TakeDamage(damage);
                }
  
            Vector3 rot = _camera.transform.rotation.eulerAngles;
  
            rot = new Vector3(rot.x, rot.y, rot.z);
  
            var midPointRay = hit.distance / 0.5f;
  
            GameObject railRay = Instantiate(_railPrefab, transform.position + new Vector3(0, 0, 0), Quaternion.Euler(rot));
  
            railRay.transform.localScale = new Vector3(railRay.transform.localScale.x, railRay.transform.localScale.y, midPointRay);
  
            Destroy(railRay, 2f);

You’ll most likely want to use “hit.point” to determine where your laser should be aiming. Assuming you’ve centered the beam in its parent properly, you could probably also just use Transform.LookAt(hit.point) to get it to rotate and aim at the exact point it hits the target.

What you are trying to do is more difficult than you probably expect.

Raycast from the center of the screen to find out the point that was shot.
Base the damage done based on the raycast from the center of the screen
Instantiate the rail effect from the tip of the gun, point it at the point that was shot using LookAt(hit.point) as the prior commented suggested.
It’s going to look strange that the rail effect won’t align with the gun itself. You either need a rail that is visually disconnected from the gun, such as a projectile that moves over time, or move the gun to the bottom center of the screen

1 Like

You should shoot your ray from the mid of your screen position like this:

Ray ray = _camera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, range)) {
  ...
  ...  
}

Why should he do that, specifically? He’s already performing the raycast from the camera’s position, directly forward. He’s not trying to raycast to the mouse position or anything. How would the approach you’re suggestion change anything?

The raycast isn’t the problem. The problem is what he’s doing with the result of the raycast.

1 Like