I have a classic “character movement” code, in which characters moves in turns controlled by independent target positions, like this:
void Update () {
if (currentMover == null) {
currentMover = this;
}
if (currentMover == this) {
chooseEnemyDir (x, z, targetX, targetZ); // method that calculate the enemy direction...
// ...and sets "targetPosition" and turns "isMoving" to true;
}
if isMoving {
transform.position = Vector3.MoveTowards (transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition) {
isMoving = false; doneMoving = true; currentMover = null;
}
}
} // end update
int chooseEnemyDir (x, z, targetX, targetZ) {
// this calculates where to move the enemy based on the player coordinates
}
Until here everything works well, but I need that at some moment (decided by a counter) the enemy moves a sector of the ground: MoveSector(). The method gets called at the beginning of the enemy turn, so when the character moves the sector, all entities in there get translated to their new positions:
void Update () {
if (currentMover == null) {
currentMover = this;
}
if (currentMover == this) {
if (canMoveSector == 10 & !isMoving & doneMoving) {
// boolean canMoveSector is defined by a "counter++"
// in this case, every 10 turns in the same sector
MoveSector(sectorToMove); // this performs the sector movement
}
chooseEnemyDir (x, z, targetX, targetZ); // method that calculate the enemy direction...
// ...and sets "targetPosition" and turns "isMoving" to true;
}
if isMoving {
transform.position = Vector3.MoveTowards (transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition) {
isMoving = false; doneMoving = true; currentMover = null;
}
}
} // end update
int chooseEnemyDir (x, z, targetX, targetZ) {
// this calculates where to move the enemy based on the player coordinates
}
void moveSector (sectorToMove) {
//moves the sector along with the entities there, and returns to move the character in turn
}
The MoveSector method recalculates all positions of the characters standing in that sector, and translate them accordingly. But I noticed that when two characters are in the same sector and one of them moves the sector, one of them moves in a wrong direction and ends up in a wrong position. That’s because (I guess) the MoveSector() method gets executed when the movement of the character hasn’t reached it’s target position. MoveSector() does it fine when none of the characters is moving. I’ve tried a lot of options but none of them works.
So what I need is to know the correct way to put the call to MoveSector “in wait” to be performed when all other characters have moved. I know that maybeit has to be done with a Coroutine and iEnumerator, but I’m not sure how to implement it. Please help.