- Home /
refactoring functions which *must* be in Update()
I want to create a function called 'slideTo(Vector3 destination)' which uses Vector3.MoveTowards() to, as the name suggests, slide a transform from its current destination to the Vector3 given as a parameter.
Here's my issue: Vector3.MoveTowards() is best used within Update(), and it would have to be called multiple times (with Time.deltaTime) to get the sliding effect I want. However, the slideTo() definition would by necessity have to be located outside of Update().
How should I resolve this paradox?
Just to be clear, here's some code that demonstrates what I'd like to happen:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
public Vector3 destination;
void Update() {
if (Input.GetKeyDown(KeyCode.WhoCares)) {
slideTo(destination);
}
}
void slideTo(Vector3 v3) {
// ...? //
// I want this sliding to take place over multiple frames,
// so that the player can actually *see* it, therefore I've ruled
// out using some form of internal loop
}
That's true, but let's say I want to make this sliding occur over, let's say one full second. is it not true that slideTo would only be called - and therefore have to run - during the single frame when the Input.Get$$anonymous$$eyDown() returned true?
Then you should use Coroutines + Lerp. It's an elegant way to do what you want.
https://unity3d.com/learn/tutorials/modules/intermediate/scripting/coroutines
Never worked with coroutines before, but I will definitely check it out
Just make sure you are not calling the coroutine every frame (with a boolean for instance)
Then, you don't know the basic way to use Lerp. There is the basic ("true") one with constant velocity, and the way the Unity's tutorial uses it (with a slow moment in the end).
See my answer on this questions for more details :
http://answers.unity3d.com/questions/998544/having-difficulty-with-lerp.html
Though, you can use Vector3.$$anonymous$$oveTowards(), it's just a matter of preference.