N1ckGreek N1ckGreek - 18 days ago 6
C# Question

How to stop a moving object exactly where i want

I created a code which calculates the difference of 2 game objects and then swaps there position by slowly moving them but i cant find a way to make them stop exactly when they reach the other object position. Any help? I tried a couple ways but i didn't manage to make them stop exactly where i wanted. Note: I want first object to stop exactly at movedSecondTilePos and second object at movedFirstTilePos.

https://www.youtube.com/watch?v=P42VB0BSBnI

The code which saves there position while they are on air and then swaps there position.

EDIT: I updated the code and i am getting very close with this code but still not 100% the same position as i want.

//Saves Moved Positions of Both Tiles
Vector3 movedFirstTilePos = firstTileObj.transform.position;
Vector3 movedSecondTilePos = secondTileObj.transform.position;

// Calculate the Difference of each Tile from the other
Vector3 firstTilePosDifference = firstTileObj.transform.position - secondTileObj.transform.position;
Vector3 secondTilePosDifference = secondTileObj.transform.position - firstTileObj.transform.position;


//Move First Tile to Second Tile Position and vise versa
while (firstTileObj.transform.position != movedSecondTilePos) {
firstTileObj.transform.position = Vector3.Lerp(firstTileObj.transform.position, movedSecondTilePos, tileMoveSpeed * Time.deltaTime);
secondTileObj.transform.position = Vector3.Lerp(secondTileObj.transform.position, movedFirstTilePos, tileMoveSpeed * Time.deltaTime);
yield return null;
}
Debug.Log ("Swaped Tiles!");

Answer

It seems like i found the solution my self :) I used this code to move both tiles as close as i can and then used the second code to move them perfectly without making it seem weird.

First Code:

firstTileObj.transform.position = Vector3.Lerp(firstTileObj.transform.position, movedSecondTilePos, tileMoveSpeed * Time.deltaTime);
secondTileObj.transform.position = Vector3.Lerp(secondTileObj.transform.position, movedFirstTilePos, tileMoveSpeed * Time.deltaTime);

Second Code:

    //Moves Perfectly Both Tiles
    firstTileObj.transform.position = originalSecondTilePos;
    secondTileObj.transform.position = originalFirstTilePos;
Comments