1
\$\begingroup\$

I've an array of gameobjects called cards and I have this code to run when clicking a button

public void mover()
{
  for (int x = 0; x < cards.Lengh; x++)
  {
    cards[x].transform.position = Vector3.Lerp(
      cards[x].transform.position, 
      new Vector3( Random.Range(2.5f, 15.5f), 1.5f, Random.Range(-5.2f, -13.5f)), 
      CardMoveSpeed * Time.deltaTime);
  }
}

But when I click on the button it moves instantly.

How can I move all of them smoothly (by using lerp)?

I read about using co-routines but I don't fully understand how to implement it in this situation.

\$\endgroup\$
4
\$\begingroup\$

The 't' quantity you specify in Vector3.Lerp is likely larger than one, causing your first problem. Secondly even if you make it smaller, your cards will never reach their destination because the 't' value will never equal 1. They'll approach it quickly at first and then slow down, but never reach the end point.

You'll need to change your functions to store the end positions you want, and also how far into the current transition we are. To do this I'll create two new variables

float cardTransition = 0.0f;
Vector3[] cardEndPositions = new Vector3[cards.Length];

Then you can change your mover function then to look like this

public void mover(Vector3[] endPositions, float transition)
{
    for (int x = 0; x < cards.Lengh; x++)
    {
        cards[x].transform.position = Vector3.Lerp(cards[x].transform.position, endPositions[x], transition);
    }
}

When you want to start a transition now, you can intialize the cardEndPositions like this

for (int x = 0; x < cardEndPositions.Length; x++)
{
    cardEndPositions[x] = new Vector3(Random.Range(2.5f, 15.5f), 1.5f, Random.Range(-5.2f, -13.5f));
}

Also make sure to update the cardTransition variable in your Update loop while a transition is occuring, add a small value to it each time step similar to what you had in the original call to Vector3.Lerp()

Update() {
    if(cardTransition < 1)
        cardTransition += CardMoveSpeed * Time.deltaTime;
}

CardMoveSpeed should be much smaller than what you have it, since currently this product is greater than 1. Tune it a bit, or use the debugger to see what values would be reasonable in here.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.