How to reset from lookAt

Hello peeps, i have issues writing code for pointing a gun at a Ray hit target position. Point work exept whent i piont at the sky the gun look at the world center position. How can i make it reset to a defalt position when pointing into infinity (without playcing walls all around)?

public class WeaponPointer : MonoBehaviour
{

    public Camera viewCam;
    public Transform aimPoint;
    [SerializeField] Image crosshairs;
    public Transform weanBasePos;
    RaycastHit hit;


    void Start()
    {
        viewCam = Camera.main;
        weanBasePos = GameObject.Find("WeaponNormPosition").GetComponent<Transform>();
    }

    
    void FixedUpdate()
    {
         
        //Ray from cam to crosshair center
        Ray ray = viewCam.ScreenPointToRay(crosshairs.gameObject.transform.position);


        // Passing hit target position to guns lookAt
        Physics.Raycast(ray, out hit, Mathf.Infinity);

        transform.LookAt(hit.point);
        Debug.DrawRay(ray.origin, ray.direction * 100, Color.red);

        if (hit.distance > 500)
        {
            transform.rotation = weanBasePos.rotation;
        }
    }
}

Raycasthit is a struct, so it cant be null. Thus it has default values. Independant of whether you hit something, you then look at hit.point. So if you hit nothing, you target the default value, ie the origin.

Raycast itself is a function returning a bool, which you can use to check if it hit something. See the examples here: Unity - Scripting API: Physics.Raycast

1 Like

I added an if statement and it works like it should, thank a lot!

1 Like