Search Unity

Rotate object to clicked location and walk there?

Discussion in 'Scripting' started by Testnia, Jun 7, 2015.

  1. Testnia

    Testnia

    Joined:
    Jul 4, 2014
    Posts:
    11
    As per title, I am unable to get a unit to move to a clicked location on the map.

    The below code is what I have done thus far. But only results in jittery movements from the unit with no odd rotation angles. I'm also hoping to clamp the y-axis so that the unit doesn't float away.

    Any help will be greatly appreciated.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Movement : MonoBehaviour {
    5.  
    6.     public float rotationSpeed = 35.0f;
    7.  
    8.     private Quaternion _lookRotation;
    9.     private Vector3 _direction;
    10.  
    11.     // Use this for initialization
    12.     void Start () {
    13.    
    14.     }
    15.    
    16.     // Update is called once per frame
    17.     void Update () {
    18.  
    19.         if (Input.GetMouseButtonDown(0))
    20.         {
    21.             RaycastHit hit;
    22.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    23.             if (Physics.Raycast(ray, out hit))
    24.             {
    25.                 if (hit.collider.tag == "Ground")
    26.                 {
    27.  
    28.                     var worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    29.                     _direction = (worldPos - transform.position).normalized;
    30.  
    31.                     _lookRotation = Quaternion.LookRotation(_direction);
    32.  
    33.                 }
    34.  
    35.                 transform.rotation = Quaternion.RotateTowards(transform.rotation, _lookRotation, rotationSpeed * Time.deltaTime);
    36.  
    37.             }
    38.           }
    39.  
    40.  
    41.     }
    42. }
    43.