I am working on unit movement for an RTS and I want to be able to keep my unit a set distance above the terrain which varies in height with hills and such. I was using a raycast from the bottom of the unit and then adjusting the height based on that. Below is the coroutine from where the function containing the height check is called:
IEnumerator Move(GameObject Unit, float targetX, float targetZ, float targetY)
{
Vector3 clickedPosition = new Vector3 (targetX, targetY + 2.5f, targetZ);
Vector3 startPosition = transform.position;
while(Vector3.Distance(startPosition, clickedPosition)>1f)
{
transform.position=Vector3.MoveTowards(transform.position, clickedPosition, 6 * Time.deltaTime);
HeightCheck();
yield return null;
}
Debug.Log("The object has reached the destination");
}
And here is the code for HeightCheck
void HeightCheck ()
{
RaycastHit hit = new RaycastHit();
if (Physics.Raycast (transform.position, Vector3.down, Mathf.Infinity))
{
Vector3 tempPos = transform.position;
if(hit.distance > 1.5)
{
//float aboveOnePointFive = transform.position.y - hit.distance + 2.5f;
tempPos.y = transform.position.y - hit.distance + 2.5f;
Debug.Log("The distance is not right from the ground");;
}
if(hit.distance < 1.5)
{
//float belowOnePointFive = transform.position.y - hit.distance + 2.5f;
tempPos.y = transform.position.y - hit.distance + 2.5f;
Debug.Log("The distance is not right from the ground");;
}
}
}
This isn’t working and I am unsure of why. I am also unsure if this is the most efficient way to go about doing something like this. Any help is much appreciated