【发布时间】:2019-02-28 05:30:05
【问题描述】:
游戏开始时,会从数组中随机选择一个航路点。然后相机应旋转以面向选定的随机航点并开始向其移动。
一旦相机到达路点,它应该等待 3 秒,然后再旋转面对并朝着下一个随机路点移动。
我的问题出在Start()。在开始向第一个航点移动之前,相机不会旋转以面对第一个航点。相反,它向后移动到第一个航路点。然后,当它到达路点时,它会等待 3 秒旋转并朝下一个路点移动。
除了相机不旋转以面对第一个选定的随机航点外,它工作正常。它在没有先旋转面对它的情况下向后移动。
这是我的代码:
航点脚本
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Waypoints : MonoBehaviour
{
public GameObject[] waypoints;
public GameObject player;
public float speed = 5;
public float WPradius = 1;
public LookAtCamera lookAtCam;
private int current = 0;
private bool rot = false;
public void Init()
{
waypoints = GameObject.FindGameObjectsWithTag("Target");
if(waypoints.Length > 0)
{
StartCoroutine(RotateFacingTarget(waypoints[UnityEngine.Random.Range(0, waypoints.Length)].transform));
}
}
void Update()
{
if (waypoints.Length > 0)
{
if (Vector3.Distance(waypoints[current].transform.position, transform.position) < WPradius)
{
current = UnityEngine.Random.Range(0, waypoints.Length);
rot = false;
StartCoroutine(RotateFacingTarget(waypoints[current].transform));
if (current >= waypoints.Length)
{
current = 0;
}
}
if (rot)
transform.position = Vector3.MoveTowards(transform.position, waypoints[current].transform.position, Time.deltaTime * speed);
}
}
IEnumerator RotateFacingTarget(Transform target)
{
yield return new WaitForSeconds(3);
lookAtCam.target = target;
rot = true;
}
}
看相机脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAtCamera : MonoBehaviour
{
//values that will be set in the Inspector
public Transform target;
public float RotationSpeed;
//values for internal use
private Quaternion _lookRotation;
private Vector3 _direction;
// Update is called once per frame
void Update()
{
//find the vector pointing from our position to the target
if (target)
{
_direction = (target.position - transform.position).normalized;
//create the rotation we need to be in to look at the target
_lookRotation = Quaternion.LookRotation(_direction);
//rotate us over time according to speed until we are in the required rotation
transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * RotationSpeed);
}
}
}
我该如何解决这个问题?
【问题讨论】:
-
你是从某个地方打电话给
Waypoints.Init()吗?我没有看到waypoints变量在哪里设置了任何值。 -
@Eliasar 是的,我有第三个脚本附加到生成航点的空 GameObject 上,在生成航点后我调用 Init() 方法。
-
作为一个命名点(命名约定),因为它运行了不止一次,我将它重命名为
RefreshWaypoints而不是Init。此外,由于您多次刷新它,您的协程将多次触发而不是等待处理。您可能有多个协同程序正在运行。