Let’s say I have a 2D rpg game (think Pokemon or old Zelda).
I want to hit “up” and have the player character smoothly walk one block up (say a block is 32 pixels, or some noticeable distance, and characters always move in units of blocks… basically Pokemon, like I said).
On beginner’s instinct I wanted to do this:
void Update() {
if(Input.GetKeyDown(KeyCode.upArrow) {
Vector2 newPos= //blah blah blah Mr Freeman
transform.position = Vector2.Lerp(oldPos, newPos, Time.deltaTime);
}
}
But obviously the problem arises that Lerp must happen continuously to appear like smooth motion, and since it is enclosed within that if statement, that will definitely not be the case, meaning the object will jump across the screen.
The obviously (and obviously bad) “solution” would be a while loop:
// Update is called once per frame
void Update () {
moveCharacter();
}
void moveCharacter() {
if(Input.GetKeyDown (right)) {
Vector2 to = //blah blah blah
while(Vector2.Distance(transform.position, to) > 3) {
transform.position = Vector2.Lerp (transform.position, to, Time.deltaTime);
}
}
}
But this raises some questions. First, it seems like Time.deltaTime doesn’t change within the same iteration of Update()? That is to say, Update() was called once, which then called moveCharacter(), which started the while loop. But since we’re still in just the first iteration of Update(), does Time.deltaTime remain accurate, so that Time.deltaTime in the beginning of a long Update() call will be different than Time.deltaTime by the end?
Also, I’m curious as to what thread this while loop sits on. If I have a lengthy while loop (never a good idea) and it’s in a script associated with this player GameObject, if it starts looping forever, what will it block? Will the whole game freeze as this while loop performs? Or is threading done intelligently?
In the end, my question is “How can I perform this translation smoothly over time without blocking other execution and without doing something needlessly complex.” Hopefully I get answers to all those other questions I asked along the way, too…
Thanks for listening.