- Home /
How can I optimize this Lerp movement in the Update Function?
I scripted a lerp animation in the Update function because my Coroutine code didn't work properly. So, in order to optimize it a bit, I tried using some guard clauses, but I don't even know if the logic is right. Is there a way to optimize it?
public GameObject[] GameMode; //end position
public GameObject startPositionGameMode; //start positions
public GameObject[] finalPositionGameMode;
public float speed = 0.5f;
float current, target;
[SerializeField] private AnimationCurve curve;
public float radius=1;
public Transform cube;
public bool animationComplete =true;
private void Update() {
CheckState();
}
private void CheckState() {
Vector3 distance = transform.position - cube.transform.position;
if (distance.magnitude <= radius) {
target = 1;
}
else {
target = 0;
}
if (!animationComplete) return;
animationComplete = false;
Animate();
Debug.LogWarning("CheckState" + animationComplete);
}
private void Animate() {
Debug.LogWarning("Animate" + animationComplete);
current = Mathf.MoveTowards(current, target, speed * Time.deltaTime);
for (int i = 0; i < GameMode.Length; i++) {
GameMode[i].transform.position = Vector3.Lerp(startPositionGameMode.transform.position, finalPositionGameMode[i].transform.position, curve.Evaluate(current));
}
animationComplete = true;
}
I have no idea what are you trying to optimize. Is it working as inteded, but too slow? Anyway, you could change if (distance.magnitude <= radius)
to if (distance.sqrMagnitude <= radiusSquared) {
To avoid the unnecessary sqrt..
Well, most of the code is run in the Update function so I thought it would be very costly. Also, for some reason, the animationComplete
variable seems to only work when it's true, and doesn't change... Maybe this will also affect the guard clauses I put up?
Sorry, my question was written very unclear. My initial question was how can I optimize the code when utilizing the Update function. But I'm more interested in whether the code logic is sturdy.
Your answer
Follow this Question
Related Questions
How to lerp an object's scale? 2 Answers
Movement Script 1 Answer
Vector3.Lerp - Constant speed between distance changes 3 Answers
Doing something wrong with lerp? 1 Answer
Physics + first person camera = jitter? 4 Answers