Looking for the optimal smooth incremental movement method.
This is an issue that I have found a lot of information on and that part of my trouble. There is so much information that I think I’m losing track of the right solution.
What I am attempting to do is smoothly move the Player object from its current location to a new location in a stepwise manner--each keypress moves a "space" in a 3d maze. After a lot of reading and not a little code borrowing I have come up with a solution that seems to work, but I’ve seen so many approaches to this that I’d really like to know what the preferred or optimal method is. I’m green enough not to trust that I’ve hacked together a good solution.
This is all being done by manipulating the position properties of the object--it's not physics-based.
In outline what I have done is this:
1. Determine end location
2. Call the coroutine SmoothMovement to handle that actual translation
3. SmoothMovement
-- Store remaining distance as a float
-- While remaining distance > 0:
-- ?? Determine an intermediate position using Vector3.MoveTowards ??
-- Translate to the intermediate position
-- Compute new remaining distance and store it
-- Yield return null
The actual code is:
private bool Move(CellCoordinates destination)
{
// Compute movement node location in adjacent cell
float scaledX = destination.X * LevelManager.scale + (LevelManager.scale / 2);
float scaledZ = destination.Z * LevelManager.scale + (LevelManager.scale / 2);
StartCoroutine(SmoothMovement(new Vector3(scaledX, cameraHeight, scaledZ)));
return true;
}
private IEnumerator SmoothMovement(Vector3 end)
{
float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
isMoving = true;
while (sqrRemainingDistance > float.Epsilon) // Close enough
{
// ??? Is this the best way to calculate an intermediate point? What about Lerp? Vector3.Distance? ???
Vector3 newPosition = Vector3.MoveTowards(transform.position, end, Time.deltaTime * speed);
// ?? Is this the right way to effect movement on the player (absent physics?) ??
transform.position = newPosition;
sqrRemainingDistance = (transform.position - end).sqrMagnitude;
yield return null;
}
transform.position = end; // avoid any drift
isMoving = false;
}
There are notes in the comments with some specific questions.
The primary one is how to best calculate the intermediate point in the SmoothMovement method. I've seen several ways to do this and my current code uses Vector3.MoveTowards. Is this the wrong method to use? What is the preferred method and why?
Secondary question is: Is just resetting the transform.position the elegant way to move an object outside physics?
Thanks!