Am trying to learn about Raycasting, and I thought I would start with something simple, and that was a laser that would come out of an object (think laser pointer in your hand) and always go to the crosshair.
Using ViewportToWorldPoint
I found it easy to cast a ray from the center of the camera, but this had an issue as you can see in this GIF below.
The line would clip through because the ray was coming from the center, not off to the side where the laser pointer would be.
Am not sure how to solve this.
void Update(){
Vector3 ray = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f));
line.SetPosition(0, transform.position);
RaycastHit hit;
if(Physics.Raycast(ray, Camera.main.transform.forward, out hit, raylength)){
if(hit.collider != null){
line.SetPosition(1, hit.point);
}
} else {
Vector3 pos = line.GetPosition(0);
line.SetPosition(1, ray + (Camera.main.transform.forward * raylength));
}
}
The closest thing I could find that I am trying to replicate for this exercise is the No Man's Sky mining tool