【发布时间】:2018-04-09 21:18:08
【问题描述】:
我有一个类,它有一个公共的变换数组,这些变换是角色可以移动到的点。每次玩家按下 A 或 D 键时,他们的角色都会平滑地移动到左侧或右侧的下一个位置,具体取决于他们是按下 A 还是 D。
我尝试这样做的方式是在玩家按下键盘上的 A 或 D 键时启动协程。然后协程将立即找到数组中的下一个左变换点,并开始使用 while 循环移动到那里。
现在我遇到的问题是能够找到最近的左/右点。我该怎么做?
到目前为止,这是我的代码:
public Transform[] positions;
public int StartPosition = 0;
private void Awake()
{
//set the start position, change the index to the one you would like the player to start at
transform.position = positions[StartPosition].position;
}
private void Update()
{
//Register Key Events
if (Input.GetKeyDown(KeyCode.A))
{
StartCoroutine(Move("Left", transform.position));
}
if (Input.GetKeyDown(KeyCode.D))
{
StartCoroutine(Move("Right", transform.position));
}
}
/// <summary>
/// Moves the player character to the next position to the left or right
/// </summary>
IEnumerator Move(string dir, Vector2 currentPosition)
{
if(dir == "Left")
{
//Find and store next left position if it exists
// HOW DO I DO THIS??????
// Go To Next Left Position
while (transform.position.x > nextLeftPos.position.x)
{
transform.position = Vector3.MoveTowards(transform.position, nextLeftPos.position, moveSpeed * Time.deltaTime);
//Come back next frame
yield return null;
}
}
}
这是我的玩家移动组件:
提前致谢
【问题讨论】: