Search Unity

Getting unit to complete rotation before moving?

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

  1. Testnia

    Testnia

    Joined:
    Jul 4, 2014
    Posts:
    11
    I've been trying to get a unit in my project to move in a fashion similiar to that of modern MOBA games.

    However, I am faced with the issue of the unit moving before the rotation is completed and the unit moving along the Y-axis.

    I have tried using a cooroutine to allow the rotation to completed first, but to no avail.
    Any help would be greatly appreciated.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Move : MonoBehaviour {
    5.  
    6.     public float smooth;
    7.     public float speed;
    8.  
    9.     private float z;
    10.     private float x;
    11.     private Vector3 targetPosition;
    12.  
    13.     // Use this for initialization
    14.     void Start () {
    15.    
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Update () {
    20.  
    21.         if (Input.GetKeyDown(KeyCode.Mouse0))
    22.         {
    23.  
    24.             speed = 1;
    25.             smooth = 20;
    26.  
    27.             RaycastHit hit;
    28.  
    29.             //var playerPlane = new Plane(Vector3.up, transform.position);
    30.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    31.  
    32.             //double hitdist = 0.0;
    33.  
    34.             if (Physics.Raycast(ray, out hit))
    35.             {
    36.                 targetPosition = hit.point;
    37.  
    38.                 x = hit.point.x;
    39.                 z = hit.point.z;
    40.                 //var targetRotation = Quaternion.LookRotation(targetPoint    - transform.position);
    41.                 //transform.rotation = targetRotation;
    42.             }  
    43.         }
    44.  
    45.  
    46.         StartCoroutine(Turn(x,z));
    47.  
    48.         //transform.position = Vector3.RotateTowards(transform.position, targetPosition, speed*Time.deltaTime, 0.0f);
    49.         transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * smooth);
    50.     }
    51.  
    52.     IEnumerator Turn(float _x, float _z)
    53.     {
    54.         Vector3 turn = new Vector3 (_x, 0, _z);
    55.         transform.Rotate(turn, speed);
    56.         yield return null;
    57.     }
    58. }
    59.  
     
  2. chubbspet

    chubbspet

    Joined:
    Feb 18, 2010
    Posts:
    1,220
    The Coroutine in this case is not really going to have any affect on line 49. Just put line 49 in an if statement and in your coroutine set the value of a Boolean e.g. bool rotating to false. That way, line 49 will only execute when rotating is false. Make sense?