Ronin6
August 4, 2012, 10:51pm
1
public Transform a;
public Transform target;
public float x = 30f; //amount of seconds for A to reach Target
I have a Transform A and a Transform target . My goal is to make A reach Target in x seconds. I have tried both Vector3.Lerp and Vector3.MoveTowards but can not figure out the problem.
Ok so Lerp will move you there in a guaranteed amount of time, but you need to record the starting position - which is trickier in Update.
float t;
Vector3 startPosition;
Vector3 target;
float timeToReachTarget;
void Start()
{
startPosition = target = transform.position;
}
void Update()
{
t += Time.deltaTime/timeToReachTarget;
transform.position = Vector3.Lerp(startPosition, target, t);
}
public void SetDestination(Vector3 destination, float time)
{
t = 0;
startPosition = transform.position;
timeToReachTarget = time;
target = destination;
}
Move any object to any place at any speed (units/seconds) or in any time – all done without using Update:
StartCoroutine (MoveOverSeconds (gameObject, new Vector3 (0.0f, 10f, 0f), 5f));
public IEnumerator MoveOverSpeed (GameObject objectToMove, Vector3 end, float speed){
// speed should be 1 unit per second
while (objectToMove.transform.position != end)
{
objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position, end, speed * Time.deltaTime);
yield return new WaitForEndOfFrame ();
}
}
public IEnumerator MoveOverSeconds (GameObject objectToMove, Vector3 end, float seconds)
{
float elapsedTime = 0;
Vector3 startingPos = objectToMove.transform.position;
while (elapsedTime < seconds)
{
objectToMove.transform.position = Vector3.Lerp(startingPos, end, (elapsedTime / seconds));
elapsedTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
objectToMove.transform.position = end;
}
JaPete
December 27, 2018, 5:05am
4
Using — public IEnumerator MoveToPosition(Transform transform, Vector3 position, float timeToMove)
{
var currentPos = transform.position;
var t = 0f;
while(t < 1)
{
t += Time.deltaTime / timeToMove;
transform.position = Vector3.Lerp(currentPos, position, t);
yield return null;
}
}
This code does not work as described above by “whydoidoit”
The code makes an object Move in 4-5 seconds, when the INPUT is 1.
BROKEN FORMULA