# timed movement/rotation

I’m trying to get an object to move from point A to point B over a given time. Let’s say 1 second for ease of use. During this time I want it to do one complete rotatoin, 360 degrees, so that it is facing the same direction when it stops moving as when it began.

I’ve been using this:

``````// Update is called once per frame
void Update () {

if(animate && transform.position != destination){
Vector3 tempPos = transform.position;

tParam += Time.deltaTime / duration;
tempPos.x = Mathf.Lerp (origin.x,destination.x,tParam);
tempPos.y = Mathf.Lerp (origin.y,destination.y,tParam);
tempPos.z = Mathf.Lerp (origin.z,destination.z,tParam);

transform.position = tempPos;

transform.Rotate(-360*Time.deltaTime,360*Time.deltaTime,0);

if(transform.position == destination){
animate = false;
}
}
}
``````

But the rotation does not complete, it does some where around 270 degrees ish. From what I have read this might be because Time.deltaTime / duration may never actually reach 1 depending on fps, but just get very close. The fact that the animate variable is being set to false implies that this is not the case though. So what am I doing wrong here? How do i get it to complete one rotation over the same duration as the movement? Thanks in advance!

The first problem is this code would only work if ‘duration’ was an integer value. That is, the sum of all the deltaTimes need to add up to 1.0, or 2.0 or 3.0. But even then, given this is a relative rotations building on relative rotation, I don’t think you would get back to the start rotation. It would work if you were only rotating on one axis and ‘duration’ was an integer value.

For two axis, local axis rotation, I’d do something that uses an absolute rotation. It gets the rotation to start and then walks through the intermediate rotations…just like you have a start position and an end position, and walk through the steps.

Also, unless this is a test for something bigger, you don’t have to do the axes independently with Mathf.Lerp(). You can use Vector3.Lerp(). Example:

``````using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
public Vector3 destination;
public float duration = 2.0f;

private Vector3 origin;
private bool animate = true;
private Quaternion q;
private float tParam = 0.0f;

void Start() {
q = transform.rotation;
origin = transform.position;
}

void Update () {

if(animate && transform.position != destination){
transform.position = Vector3.Lerp(origin, destination, tParam);
transform.rotation = q * Quaternion.AngleAxis(-360 * tParam, Vector3.right) * Quaternion.AngleAxis(360 * tParam, Vector3.up);
tParam += Time.deltaTime / duration;

if(transform.position == destination){
animate = false;
}
}
}
}
``````