I have a coroutine setup up for making units in my RTS game move to a right mouse click but it is not working correctly. If I right click too soon after right clicking for the first time the unit will stop and it doesn’t move at a consistent rate, it will slow down as it gets closer to the destination.
Ideally I would have the unit move at a consistent rate from it’s starting point to the clicked point and have it able to change the destination while it is moving. Below is my current code
using UnityEngine;
using System.Collections;
public class UnitControl : MonoBehaviour {
public GameObject[] Units;
// Use this for initialization
void Start ()
{
}
bool unitMoving = false;
IEnumerator Move(GameObject Unit, Vector3 target)
{
while(Vector3.Distance(transform.position, target)>0.005f)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
transform.position=Vector3.Lerp(transform.position, target, 3.0f*Time.deltaTime);
yield return null;
}
unitMoving = false;
}
// Update is called once per frame
void FixedUpdate ()
{
float moveSpeed = 5.1f;
if (Input.GetMouseButtonDown (1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast (ray, out hit))
{
Vector3 movePos = new Vector3 (hit.point.x, 1.5f, hit.point.z);
isSelectedScript isSelectedScript = GetComponent<isSelectedScript>();
Debug.Log("Debug working before isSelected loop");
if (isSelectedScript.isSelected == 1)
{
Debug.Log("This is between the if and the while loops");
transform.LookAt(hit.point);
StartCoroutine(Move(gameObject, hit.point));
// while(Vector3.Distance(transform.position, hit.point)>0.005f)
// {
// transform.position=Vector3.Lerp(transform.position, hit.point, 10.0f*Time.fixedDeltaTime);
// }
}
}
}
}
}