Search Unity

Resolved How to determine where to rotate towards (or look) if raycast does not hit?

Discussion in 'Animation' started by monahajt, Oct 21, 2022.

  1. monahajt

    monahajt

    Joined:
    Nov 28, 2017
    Posts:
    15
    Okay so I have a script attached to a player. I want them to rotate toward the crosshair position wherever it goes on screen. Thus far I have seen a lot of people do this with a raycast. But this only works if there is a hit. How do I determine the rotation if there is no hit, using a default distance of 1000.0f;

    Code (CSharp):
    1. RaycastHit hit;
    2. RectTransform crosshair = aimTarget.GetComponent<RectTransform>();
    3. Ray ray = Camera.main.ScreenPointToRay(crosshair.position);
    4.  
    5. Vector3 direction = Vector3.forward;
    6.  
    7.  if (Physics.Raycast(ray, out hit, 1000.0f))
    8. {
    9.     Debug.Log("yes");
    10.     direction = hit.point - transform.position;
    11. }
    12. else
    13. {
    14.     Debug.Log("no");
    15.     // direction = ?
    16. }
    17.  
    18. transform.rotation = Quaternion.LookRotation(direction);
    19. Debug.DrawRay(transform.position, direction, Color.green);
     
  2. monahajt

    monahajt

    Joined:
    Nov 28, 2017
    Posts:
    15
    I actually figured this out. In the else block I needed

    Code (CSharp):
    1. direction = Camera.main.ScreenToWorldPoint(new Vector3(crosshair.position.x, crosshair.position.y, Camera.main.nearClipPlane + 1000f));