- Home /
Making a smooth camera translation and rotation, C#
Hey there!
I'm trying to make a smooth camera translation and rotation, where the camera with the Script moves to a set of pre-determined coordinates after the pressing of a button. I've part of it working, however, when I press to advance, it looks more like changing the slide of a presentation then actually a smooth translation/rotation. Here's the code:
void MoveObject (Transform thisTransform, Vector3 startPos, Vector3 endPos, Quaternion startRot, Quaternion endRot, float time) {
float i = 0;
float rate = 1/time;
while (i < 1) {
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
thisTransform.rotation = Quaternion.Slerp (startRot, endRot, i);
} }
So, what do I need to change in order for it to work?
Thanks in advance.
JPB18
That's because your executing it in a while loop, that means you'll have the translation/rotation done in just one frame(Someone correct me if I'm wrong). You probably should consider doing it in the Update function using thisTransform.Translate and the function you're already using, Quaternion.Slerp.
Answer by aldonaletto · Jun 04, 2012 at 04:27 PM
This function should be a coroutine to work smoothly: each while iteration should wait for the next frame (which means yield). You should also have a bool variable to tell you when the coroutine is running - coroutines run automatically in the background, and you will need some way to know when MoveObject has finished:
bool moving = false;
IEnumerator MoveObject (Transform thisTransform, Vector3 startPos, Vector3 endPos, Quaternion startRot, Quaternion endRot, float time){
moving = true; // MoveObject started
float i = 0;
float rate = 1/time;
while (i < 1) {
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
thisTransform.rotation = Quaternion.Slerp (startRot, endRot, i);
yield return 0;
}
moving = false; // MoveObject ended
}
// call it with StartCoroutine:
if (!moving){ // never start a new MoveObject while it's already running!
StartCoroutine(MoveObject(....));
}