Unity:使相机仅沿x方向跟随玩家

时间:2014-11-30 16:53:25

标签: c# unity3d

我正在使用以下脚本,它使相机跟随播放器(在x和y方向):

using UnityEngine;
using System.Collections;

public class Camera2DFollow : MonoBehaviour {

    public Transform target;
    public float damping = 1;
    public float lookAheadFactor = 3;
    public float lookAheadReturnSpeed = 0.5f;
    public float lookAheadMoveThreshold = 0.1f;

    float offsetZ;
    Vector3 lastTargetPosition;
    Vector3 currentVelocity;
    Vector3 lookAheadPos;

    // Use this for initialization
    void Start () {
        lastTargetPosition = target.position;
        offsetZ = (transform.position - target.position).z;
        transform.parent = null;
    }

    // Update is called once per frame
    void Update () {

        // only update lookahead pos if accelerating or changed direction
        float xMoveDelta = (target.position - lastTargetPosition).x;

        bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;

        if (updateLookAheadTarget) {
            lookAheadPos = lookAheadFactor * Vector3.right * Mathf.Sign(xMoveDelta);
        } else {
            lookAheadPos = Vector3.MoveTowards(lookAheadPos, Vector3.zero, Time.deltaTime * lookAheadReturnSpeed);  
        }

        Vector3 aheadTargetPos = target.position + lookAheadPos + Vector3.forward * offsetZ;
        Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref currentVelocity, damping);

        transform.position = newPos;

        lastTargetPosition = target.position;       
    }
}

但是,我只希望它在x方向上跟随玩家。已经玩了一段时间的脚本,但无法搞清楚。

1 个答案:

答案 0 :(得分:1)

这似乎是示例资产中提供的脚本,可能比您需要的更复杂。

我通过简单地使用以下内容实现了您之前尝试做的事情:

void Update () {
    transform.Translate(Vector3.right * Time.deltaTime * movementSpeed);
}

这是来自附加到主摄像头的脚本。