public void Update() { // when the monster moves to the target position, // we need to start to move to the next position again and again. if (transform.position == new Vector3(targetPosition.x, targetPosition.y, 0)) { // Remove the cost of tile on the start position toggleCostOfTile(toPosition(currentPosition), false); // Add the cost of tile on the target position toggleCostOfTile(toPosition(targetPosition), true); // Notify the player through notification system that the monster now in a new position. NotificationSystem.publish(new MonsterMoveEvent(this, toPosition(currentPosition), toPosition(targetPosition))); // Now the arrived target position becomes the start position for the next move. currentPosition = targetPosition; // Retrive the target position for the next move. targetPosition = movingArea.getNextRandomPosition(transform.position); } float distance = Vector2.Distance(transform.position, targetPosition); float duration = Time.time - startTime; float distCovered = duration * speed; transform.position = Vector2.Lerp(transform.position, targetPosition, distCovered / distance); startTime = startTime + duration; }