- Home /
How do I find the correct speed when using Vector3.MoveTowards and Quaternion.RotateTowards together?
I'm using a Coroutine that moves, rotates, and scales one transform into another transform using Vector3.MoveTowards and Quaternion.RotateTowards.
What I'd like to do is measure the amount of change each of these operations requires and set the speeds so that they all complete at (roughly) the same frame.
I have a struct that stores 3 floats for the respective speeds. As a bonus, it would be nice to have an "overall speed" float that could be adjusted to control how quickly all three changes are made.
IEnumerator MorphTransform(Transform final, Speeds speeds)
{
while(transform.position != final.position ||
transform.rotation != final.rotation ||
transform.localScale != final.localScale)
{
transform.position = Vector3.MoveTowards(transform.position,
final.position,
speeds.transposeSpeed * Time.deltaTime);
transform.rotation = Quaternion.RotateTowards(transform.rotation,
final.rotation,
speeds.rotateSpeed * Time.deltaTime);
transform.localScale = Vector3.MoveTowards(transform.localScale,
final.localScale,
speeds.scaleSpeed * Time.deltaTime);
yield return null;
}
}
[System.Serializable]
public struct Speeds
{
public float transposeSpeed;
public float rotateSpeed;
public float scaleSpeed;
}
Thanks for your time and response in advance!
This doesn't make sense, your coroutine doesn't perform like a coroutine, it just runs once then it's done. Without a yield for seconds it isn't going to perform much action. Also, movetowards is a bit like a lerp, so it's kind of useless without being scaled itself. Honestly I'd just use a basic Vector3.Lerp
, and Quaternion.Slerp
. You can scale both by the same time scale and it would be a breeze. If you don't know how lerps work, here is a quick example. Remember this is only an example, but you should get the idea.
Vector3 startPos;
Vector3.endPos;
float scale;
void LerpVector(float time)
{
scale += time;
transform.position = Vector3.Lerp(startPos, endPos, scale);
}