0
\$\begingroup\$

I am making a board game where the players hit a dice and move on an array of GameObjects according to the number they got.

So I declared a Gameobject array and added to it all the objects I need.

The problem is that when the player moves, he is going immediately to the target.

What I want is to make the player move through the Gameobject array, object by object, till it reaches the target(which is defined according to the dice number).

Here is what I am trying (using C#):

for(int i=0;i<spaces.Length;i++)
{
    transform.position = Vector3.MoveTowards(transform.position,
    spaces[currentPosition+diceResult].transform.position,Time.deltaTime / smooth );
}

spaces is the name of GameObject[] array.

currentPosition is the position of player before hitting the dice.

diceResult is the number he got in the dice.


EDIT :

I solved it!

Here is how it worked:

 if (index < spaces.Length)
 {
       transform.position = Vector3.MoveTowards(transform.position,
       spaces[index].transform.position, Time.deltaTime *smooth);

       //If we've reached the destination, move to the next one
       if (transform.position == spaces[index].transform.position) 
            index++;
 }
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

the problem with your "for" code , that I think you placed inside the Update(), is that it get executed in one update cicle. In Unity you must think the Update as a 'frame' execution. Plus, that for seems useles. Where do you use the "i" variable?

So you must do something like this into the Update(), (I missed the starting and end management)

//small dist is a float value greater of 0 but not to big that you must initialize in the //Start()
if ((transform.position - spaces[currentPosition+i].position).magnitude < smalDist)
{
 // I reached next element 

 if (i==diceResult){
   //reached destination
   // STOp The movement 
 }
 i++;
 transform.position = Vector3.MoveTowards(transform.position,
    spaces[currentPosition+i].transform.position,Time.deltaTime / smooth );
}
\$\endgroup\$
3
  • \$\begingroup\$ Yeah I placed the for loop in Update(). I tried using your code but I got this error: Operator '-' cannot be applied to operands of type UnityEngine.Vector3' and UnityEngine.GameObject' \$\endgroup\$
    – Michael
    Commented Mar 7, 2015 at 20:15
  • \$\begingroup\$ And I should place your code in the for loop right? \$\endgroup\$
    – Michael
    Commented Mar 7, 2015 at 20:27
  • \$\begingroup\$ (transform.position - spaces[currentPosition+i].position) ops forgot ".position". And No, the for is useles. And you can't hope to add my code and make things work. You must manage the Starting movement and End movement ... \$\endgroup\$ Commented Mar 7, 2015 at 20:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .