I made a random dice for a board game now i want to move my piece according to roll of dice. I want to don’t want to move in second. I want to move with some velocity and want to stop it at a specific point.
if (DiceRoll == 2) {
transform.position = new vector3(2, 5, 8);
}
Use Vector3.Lerp for interpolating the position over time. AnimationCurves can be used so the transition isn’t exclusively linear.
public AnimationCurve curve = AnimationCurve.EaseInOut(0,0,1,1);
IEnumerator MoveTo(Vector3 newPos)
{
Vector3 startPos = transform.position;
float elapsed = 0f;
while (elapsed < 1f)
{
elapsed = Mathf.Clamp(elapsed + Time.deltaTime, 0, 1);
transform.position = Vector3.Lerp(startPos, newPos, curve.Evaluate(elapsed));
yield return null;
}
}
Here’s an example using Vector3.Lerp and a Coroutine. I suggest clicking the links to read the usage of both before using this code.
// Move piece within 2 seconds
float pieceMoveTime = 2f;
SomeOtherMethodYouMade()
{
if (DiceRoll == 2)
{
StartCoroutine(MovePiece(new Vector3(2, 5, 8)));
}
}
IEnumerator MovePiece(Vector3 newPosition)
{
float elapsedTime = 0f;
while (elapsedTime < pieceMoveTime)
{
transform.position = Vector3.Lerp(transform.position, newPosition, elapsedTime / pieceMoveTime);
elapsedTime += Time.deltaTime;
yield return null;
}
}