In my project I’m using a laser which is just a linerenderer with a raycast, it is supposed to adjust the 2nd position of the LineRenderer component with the raycast distance (hit.distance), but the distance is always way too short. When the Raycast says the disance is 9 it is actualy 13 (and 3 is actualy 4). So its not that it is placed too far back because the offset is relative…
This is my code.
using UnityEngine;
using System.Collections;
public class Laser : MonoBehaviour {
private LineRenderer lr;
// Use this for initialization
void Start () {
lr = GetComponent<LineRenderer>();
}
// Update is called once per frame
void Update () {
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit))
{
if (hit.collider)
{
lr.SetPosition(0, new Vector3(0, 0, 0));
lr.SetPosition(1, new Vector3(0, 0, hit.distance));
}
}
else
{
lr.SetPosition(1, new Vector3(0, 0, 1000));
}
}
}
Could anyone please tell me what is wrong with my code?
btw.
I have tried it using vector3
// instead of hit.disance something along the lines of:
Vector3 laserDistance = hit.collider.transform.position - transform.position;
I think (hit.collider.transform.position- transform.position).sqrMagnitude is also distance, although ive never used that method, despite hearing its fastest of the lot
sqrMagnitude is mainly useful/faster for comparing distances, such as if vector1.sqrMagnitude > vector2.sqrMagnitude. sqrMagnitude doesnt give you the actual useful distance, it gives you the distance squared. This means if you know the distance you want to compare sqrMagnitude with, you can do it like vector1.sqrMagnitude == distance * distance.
Also, dont use the collider transform for the distance, use the actual hit.point.
(vector1 - vector2).magnitude gives the same result as the Vector3.Distance method, though I am not sure if one is more optimized for the square root operation.
To OP, I am unsure as to what you mean by “When the Raycast says the disance is 9 it is actualy 13”. How were you able to tell it was actually 13? You debug.log the hit.distance and it returned 9 while in the scene view you checked yourself to see it was 13?
What happens if you do this
If the line doesnt seem its hitting the right object or the two distances dont match, then there might be an issue with how the cast is detecting your collider, possible causes are too large objects or weirdly scaled objects.