Search Unity

[SOLVED]Move camera to ray hit.point, but get hit object center

Discussion in 'Scripting' started by SiMULOiD, Apr 26, 2020.

  1. SiMULOiD

    SiMULOiD

    Joined:
    Dec 23, 2013
    Posts:
    126
    Hi all,
    I'm happy with the result of the below script- moves the camera to a hit.point.
    What I'd really like to do is move my camera to the center (pivot) of an raycast hit game object.
    Appreciate your suggestions.


    Code (CSharp):
    1.      void Update ()
    2. {
    3.  if (Input.GetMouseButtonDown(0)){
    4. Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    5. RaycastHit hit = new RaycastHit ();
    6. if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition),  out hit, Mathf.Infinity) && hitInfo.collider)  
    7. gameObject.transform.position =  hit.point;
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Instead of:
    Code (CSharp):
    1. gameObject.transform.position =  hit.point;
    do
    Code (CSharp):
    1. gameObject.transform.position =  hit.transform.position;
     
    SiMULOiD likes this.
  3. SiMULOiD

    SiMULOiD

    Joined:
    Dec 23, 2013
    Posts:
    126
    Thanks, PraetorBlue!