在Unity3D中夹紧摄像机前进和后退矢量

时间:2016-07-13 16:51:14

标签: c# unity3d camera

我的透视相机在x轴上旋转。我用滚轮实现了变焦,效果很好。

然而,我正试图限制缩放。我现在的解决方案是采用transform.forward y和z分量的相对比例,并使用Mathf.Clamp并乘以minZoom和{{1}来锁定相机的y和z位置由相应的maxZoom组件浮动。它工作得很好,除了它限制了y轴,所以当我转换时我不能低于给定的y,因为我的夹子理想地只是影响缩放。

有没有办法夹住相机的前后移动?我一直在寻找无处不在的东西。

感谢。

修改

这是相关代码(我的钳制发生在LateUpdate中):

transform.forward

1 个答案:

答案 0 :(得分:1)

工作代码:

using UnityEngine;
using System.Collections;

public class ClickManager : MonoBehaviour
{
    public float dragSpeed = 2;
    public float minZoom = 0.5f;
    public float maxZoom = 5.0f;

    private Vector3 dragOrigin;

    private float lerpPercentBack = 0; 
    private float lerpPercentForward = 0;
    private bool isLerpingBack = false;
    private bool isLerpingForward = false;

    Vector3 forwardPos;
    Vector3 backwardPos;
    void Start()
    {
        forwardPos = transform.position ;
        forwardPos.z += maxZoom;

        backwardPos = transform.position ;
        backwardPos.z += minZoom;
    }


    void Update()
    {
        float scroll = Input.GetAxis("Mouse ScrollWheel");

        if (Input.GetMouseButtonDown(1))
        {
            dragOrigin = Input.mousePosition;
            return;
        }

        if (scroll > 0)
        {
            isLerpingForward = true;
            lerpPercentForward = 0;
        }
        if (scroll < 0)
        {
            isLerpingBack = true;
            lerpPercentBack = 0;
        }



        if (isLerpingBack)
        {
            scrollLerperBack();
            lerpPercentBack += 0.05f;

            if (lerpPercentBack >= 1.0f)
            {
                lerpPercentBack = 0;
                isLerpingBack = false;
            }
        }


        if (isLerpingForward)
        {

            scrollLerperForward();
            lerpPercentForward += 0.05f;

            if (lerpPercentForward >= 1.0f)
            {
                lerpPercentForward = 0;
                isLerpingForward = false;
            }
        }
    }


    void scrollLerperBack()
    {
        transform.position = Vector3.MoveTowards(transform.position, backwardPos, Time.deltaTime * dragSpeed );
    }


    void scrollLerperForward()
    {
        transform.position = Vector3.MoveTowards(transform.position, forwardPos, Time.deltaTime * dragSpeed);
    }


}