- Home /
This question was
closed Aug 21, 2020 at 01:34 PM by
KorniXPL for the following reason:
The question is answered, right answer was accepted
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);
Comment
Best Answer
Answer by Llama_w_2Ls · Aug 20, 2020 at 08:55 AM
I believe that you can use transform.LookAt() to always make your laser face the center of the screen. If you fire a raycast and set the transform of your laser to always look at the hit.point, or the point in world space where your raycast is colliding, the laser should always be facing the center of the object youre looking at. For example:
public Camera cam;
public GameObject LaserPointer;
private void Update()
{
RaycastHit laser;
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out laser))
{
LaserPointer.transform.LookAt(laser.point);
}
}
@KorniXPL Let me know if it works.