Coroutine中的Slerp相机

时间:2016-11-04 11:58:37

标签: c# unity3d game-engine

我的相机不是目标gameObject的孩子。我必须将Slerp Camera添加到我的可移动游戏对象中。我使用Coroutine作为在FixedUpdate()中工作的。我尝试在Update()中编写它,但无论如何它都不能很好地工作(我猜有框架兼容性的问题)。帮我改进代码。提前谢谢。

// Public parameters
public GameObject player;
public float maxDistance = 3f;

// Positions for Slerp
private Vector3 startPosition;
private Vector3 endPosition;

// Components
private Transform playerTransform;
private Transform thisTransform;
private float timeSinceStarted;

void Awake () {
    playerTransform = this.player.transform;
    thisTransform = this.transform;
}

void Update ()
{
    this.transform.LookAt (player.transform);
    startPosition = thisTransform.position;

    endPosition = new Vector3 (playerTransform.position.x, playerTransform.position.y + 3.5f, playerTransform.position.z);

    if (MoveStates.Instance.mustWalkBackward ()) {
        endPosition = new Vector3 (playerTransform.position.x, playerTransform.position.y, playerTransform.position.z);
    }

    if (MoveStates.Instance.mustWalkForward ()) {
        endPosition = new Vector3 (playerTransform.position.x, playerTransform.position.y + 2f, playerTransform.position.z);
    }
    timeSinceStarted = 0f;
    StartCoroutine (MoveFunction ());
}

IEnumerator MoveFunction()
{   yield return new WaitForSeconds (Mathf.Epsilon);
    timeSinceStarted += Time.deltaTime;
    if (Vector3.Distance (startPosition, endPosition) > maxDistance) {
        this.thisTransform.position = Vector3.Slerp (this.startPosition, this.endPosition, timeSinceStarted);
    }
}

1 个答案:

答案 0 :(得分:0)

我猜您以错误的方式使用 Coroutine 。我建议这样做:

IEnumerator MoveFunction()
{   
    while (Vector3.Distance (startPosition, endPosition) > maxDistance)
    {
        transform.position = Vector3.Slerp (startPosition, endPosition, Time.deltaTime);
        yield return new WaitForEndOfFrame();
    }
}

但如果您只想准时移动相机,则可以使用此选项。在你的情况下,我不会使用 Coroutine ,我想你想要&#34;关注&#34;您的播放器持续:您应该使用 Update / FixedUpdate / LateUpdate 方法中的 Slerp (当涉及到<时,我首选 LateUpdate 强>相机位置调整。我想这样的东西应该足够了:

void LateUpdate()
{
    if (Vector3.Distance (startPosition, endPosition) > maxDistance)
    {
        transform.position = Vector3.Slerp (startPosition, endPosition, Time.deltaTime);
    }
}

顺便说一下:您只需拨打tranform而不是this.transformstartPosition而不是this.startPosition