How do I make an object move smoothly?
I'm making a multiplayer chess game and I want to make the pieces move smoothly to their destination. Currently I'm using the transform.position method for changing their position. I tried using the transform.Translate method in the following way:
[Command]
public void CmdMoveWpawn5 (int x, inty);
{
float speedx = (x - Wpawn5.transform.position.x) / 10000;
float speedy = (y - Wpawn5.transform.position.y) / 10000;
while (Wpawn5.transform.position.x < x || Wpawn5.transform.position.y < y)
{
Wpawn5.transform.Translate(speedx * Time.deltaTime, speedy * Time.deltaTime, 0);
}
}
Where x and y are the coordinates where the pawn is supposed to move. However instead of moving smoothly, after clicking, the pawn waits a few seconds and then teleports to the destination. I experimented with different Network Send Rates and tried changing the Movement Threshold, the Snap Threshold and the Interpolate Mover, but the same problem persisted. I'm sure this problem has an easy solution, but I just can't seem to find it. I would be really grateful if someone could help me out.
Answer by JedBeryll · May 05, 2018 at 05:01 AM
A while loop is executed in a single frame so you would normally not get the desired effect. There are several ways that work though - putting it in Update, using InvokeRepeating or using a coroutine. I suggest a coroutine because you have the most control over it.
This should work:
//target: the transform we are moving
//movePosition: the expected final position of the target
//moveTime: how long it takes to move the target
public IEnumerator MoveOverTime(Transform target, Vector3 movePosition, float moveTime) {
Vector3 startPosition = target.position;
float elapsedTime = 0;
while (elapsedTime < moveTime) {
//add last frame time to the elapsed time
elapsedTime += Time.deltaTime;
//t is used to put the elapsed time in a value between 0-1, meaning: 0%-100%
float t = elapsedTime / moveTime;
//lerp will move the position to t % between the 2 points
target.position = Vector3.Lerp(startPosition, movePosition, t);
//yield return null in a Coroutine will stop execution until the next frame
yield return null;
}
}
And you start it like this: StartCoroutine(MoveOverTime(Wpawn5.transform, new Vector3(x, y), 1f));