使相机仅在Y轴上跟随目标?

时间:2016-02-02 21:25:47

标签: c# unity3d

下面的脚本(附在主摄像头上)使摄像机顺利地跟踪特定目标。但它遵循x和y轴上的目标。我们必须做出哪些更改才能使相机仅在Y轴上跟踪目标,同时永远保持其原始x轴?

public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;

void Start () {
    targetPos = transform.position;
}

void LateUpdate () {

    if (target)
    {
        Vector3 posNoZ = transform.position;
        posNoZ.z = target.transform.position.z;

        Vector3 targetDirection = (target.transform.position - posNoZ);

        interpVelocity = targetDirection.magnitude * 5f;

        targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime); 

        transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
    }
}

3 个答案:

答案 0 :(得分:1)

您只需指定Y轴而不是整个矢量即可。你可以尝试类似的东西,

void LateUpdate () {

    if (target)
    {
        Vector3 posNoZ = transform.position;
        posNoZ.z = target.transform.position.z;

        Vector3 targetDirection = (target.transform.position - posNoZ);

        interpVelocity = targetDirection.magnitude * 5f;

        Vector3 factorTowardsTarget = (targetDirection.normalized * interpVelocity * Time.deltaTime);

        targetPos = new Vector3(transform.position.x,transform.position.y + factorTowardsTarget.y,transform.position.z); 

        transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
    }
}

答案 1 :(得分:0)

尝试用IModel<IFactoryItem>替换最后一行代码我的C#团结有点生疏,告诉我这是否有用。

为了保持vector3.lerp,另一种可能的替代方法就是在你分配x值的地方写transform.position.y = targetPos + offset;

答案 2 :(得分:0)

在你的最后一行,而不是

transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);

...试试这个:

Vector3 targetVec = targetPos + offset;
transform.position = Vector3.Lerp(transform.position,
                                  new Vector3(transform.position.x, targetVec.y, targetVec.z),
                                  0.25f);

在这里,我正在改变Vector-lerp的目标,使其具有我们想要的y和z,但保留原始变换的x-coord。

我希望有所帮助!