I have read literally over 20 articles on this issue, but had no luck. I just started Unity so maybe that’s the reason.
My aim:
Make the character ‘walk’ to the position where the user taps. For now, just moving the sprite there without any animation will do. For example my player is in point A, and I tap in point B. It will smoothly move from point A to B.
Issue:
I just can’t seem to get it right. I can make it jump there (as in teleport) but haven’t had any luck with the smoothness. I am using
To make it move smoothly, you can’t use just a single line of code; you need to move it a little bit each frame. There are a couple of ways to approach that, but my preferred method is to set a target, and then use the Update method (one of the magic callback methods on MonoBehaviour) to move it a little bit each frame, e.g. using Vector3.Lerp.
For example, here’s some code typed out of my head… apologies in advance for any typos, but perhaps it will point you in the right direction:
// Properties you should set when the screen is touched:
Vector3 targetPosition; // where we're going
float targetTime; // when we want to get there
Vector3 startPosition; // where we started from
float startTime; // what time we started
// Update method actually does the work:
void Update() {
float t = (Time.time - startTime) / (targetTime - startTime);
if (t <= 1) transform.position = Vector3.Lerp(startPosition, targetPosition, t);
}
“t” is the standard name for a time parameter, in this case, the time (from 0 to 1) between the start position and the end position. You pass this to Lerp, and Lerp does a linear interpolation (“lerp” for short) between the start and end points.
However, I must have been sleepy last night… I realized today that this is the hard way of doing it. Unity provides a much simpler method that works fine in this case: Vector3.MoveTowards.
In fact, the sample code given in the documentation (at the link above) does exactly what you want: moves the object towards a target position, at some speed. You should be able to drop this right in, and simply set the target to wherever you want to move. My apologies for giving you a more complex approach yesterday, but maybe knowing about Lerp will come in handy in the future!