2
我正在努力使單元在Unity2d中通過網格移動。我得到了運動沒有問題的工作。 我希望MovePlayer函數等到協程完成後再繼續下去,所以程序會一直等到玩家完成移動後再發出更多的訂單。在繼續使用函數C#Unity之前等待協程完成
這裏是我的代碼: 公共類球員:MonoBehaviour {
public Vector3 position;
private Vector3 targetPosition;
private float speed;
void Awake()
{
speed = 2.0f;
position = gameObject.transform.position;
targetPosition = position;
GameManager.instance.AddPlayerToList(this); //Register this player with our instance of GameManager by adding it to a list of Player objects.
}
//Function that moves the player, takes a list of nodes as path
public void MovePlayer(List<Node> path)
{
StartCoroutine(SmoothMovement(path));
//Next step should wait until SmoothMovement is finished
}
private IEnumerator SmoothMovement(List<Node> path)
{
float step = speed * Time.deltaTime;
for (int i = 0; i < path.Count; i++)
{
targetPosition = new Vector3(path[i].coordinatesX, path[i].coordinatesY, 0f);
float sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;
while (sqrRemainingDistance > float.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;
yield return null;
}
position = transform.position;
}
}
謝謝你,你說了什麼給了我一個關於如何處理我的問題的想法,謝謝:) –