- Home /
working on a board game
Hi everybody,
I am working on a board game and trying to move the player on the fields. I have this code and want to update it to achieve further goals:
public class playerControl : MonoBehaviour
{
public Transform [] fieldsArray;
//public Vector3 offset = new Vector3(-5, 2, -7);
int arrayIndex = 0;
public float speed = 25;
int numberOfMoves = 6;
private float yPosAtStart;
private void Start()
{
yPosAtStart = transform.position.y;
transform.position = fieldsArray[arrayIndex].transform.position;
}
void playerMove()
{
transform.position = Vector3.MoveTowards(transform.position, fieldsArray[numberOfMoves].transform.position, speed * Time.deltaTime);
if(transform.position == fieldsArray[arrayIndex].transform.position)
{
arrayIndex++;
}
if(arrayIndex == fieldsArray.Length)
{
arrayIndex = 0;
}
transform.position = new Vector3(transform.position.x, yPosAtStart, transform.position.z);
}
void Update()
{
playerMove();
}
}
I need some help with two things:
I would like to achieve an effect for the player to move from A to B by touching every waypoint. For example now if I change the number of moves to more than 7 the player straight away moves to the 8th field and I do not want it like this. If the number of moves is for example 14 I want to achieve an effect of the player touching every waypoint up to field 14 not just going to the 14th field straight away.
So I want the player to move on the fields but with a kind of delay, I want to set up a certain speed and I want the player to touch one field wait a little bit and after a certain amount of time move to the next one and so on.
Thank you very much for the help
Tamas
Answer by metalted · Dec 06, 2021 at 09:13 PM
Are you sure that the following code is what you want?
transform.position = Vector3.MoveTowards(transform.position, fieldsArray[numberOfMoves].transform.position, speed * Time.deltaTime);
When the code runs, we instantly move to the field defined in the "numberOfMoves" variable. If you want to start at the first field and 'walk' over all the fields to the destination, you might want to have:
transform.position = Vector3.MoveTowards(transform.position, fieldsArray[arrayIndex].transform.position, speed * Time.deltaTime);
We now start at field 0, when we arrive we increment "arrayIndex" and move to field 1, repeating until we are at the tile we want.
Quick note: You don't have to call fieldsArray[...].transform.position because every element in the array is already a Transform. fieldsArray[...].position will give you the same value. It's like typing transform.transform.position.
Your answer
![](https://koobas.hobune.stream/wayback/20220612231311im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make grid on circle sprites? 1 Answer
yield for animation 0 Answers
Board Game Movement 0 Answers
Move while jump on board 0 Answers
Change position of a text prefab added to a world space canvas via scripting 0 Answers