I’m trying to write a coroutine to move my blocks on the X axis at a certain speed until they reach a precise spot. I can’t use Lerp because it isn’t precise and I would like to base the animation on speed and not time.
My math sucks and I tried a lot of different ways, but floats are making my life really difficult.
Can someone help me?
using UnityEngine;
using System;
using System.Collections;
public class QuadB : MonoBehaviour
{
[SerializeField] Transform A = null;
[SerializeField] Transform B = null;
[SerializeField] float speed = 10;
void Start ()
{
StartCoroutine("me");
}
IEnumerator me()
{
float t = Mathf.Abs(transform.position.x - B.position.x);
float direction = (t) / (Mathf.Abs(t));
Debug.Log ("direction " + direction);
float x = -8;
while (x != 8)
{
float i = (float)Math.Round((Time.deltaTime * speed) / t, 2);
x += i;
x = (float)Math.Round(x, 2);
transform.position = new Vector3(x, transform.position.y);
Debug.Log("i " + i + " x " + x);
yield return null;
}
}
}
Edit: Corrected code formatting