增加Vector3的Y值

本文关键字:Vector3 增加 | 更新日期: 2023-09-27 18:13:19

我现在正在用Unity重新学习3D数学,并修改示例相机控制器。默认情况下,它聚焦在一个目标上,在这个例子中是玩家,但是我想给它添加一个偏移量,使它聚焦在玩家的头部上方。

namespace UnityStandardAssets._2D
{
    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;
        private float m_OffsetZ;
        private Vector3 m_LastTargetPosition;
        private Vector3 m_CurrentVelocity;
        private Vector3 m_LookAheadPos;
        // Use this for initialization
        private void Start()
        {
            m_LastTargetPosition = target.position;
            m_OffsetZ = (transform.position - target.position).z;
            transform.parent = null;
        }

        // Update is called once per frame
        private void Update()
        {
            // only update lookahead pos if accelerating or changed direction
            float xMoveDelta = (target.position - m_LastTargetPosition).x;
            bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;
            if (updateLookAheadTarget)
            {
                m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
            }
            else
            {
                m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
            }
            Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
            Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);
            transform.position = newPos;
            m_LastTargetPosition = target.position;
        }
    }
}

我想我可以简单地添加以下几行,但是这样做时相机垂直飞离屏幕。这种方法有什么问题,我如何才能使这种抵消实际工作?

    Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);
    Vector3 newPos2 = new Vector3(newPos.x, newPos.y + 1, newPos.z);
    transform.position = newPos2;

增加Vector3的Y值

这个问题可以通过为玩家添加子GameObject并将其设置为所需位置来解决,然后将其用作相机目标。

而且,这样做会使进一步的位置更改更容易执行。

你正在使用相机的位置(即transform.position)来计算相机的新位置:

Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);

,然后在接下来的两行中增加新位置的y,然后将其重新分配给相机变换位置。因此,每一帧相机的y轴位置都会增加,导致它向上"飞"。

您可以在Start()方法中设置相机所需的y位置,并且在计算过程中不更改它

void Start() 
{
    Vector3 cameraPos = transform.position;
    cameraPos.y += 1;
    transform.position = cameraPos;
}

只要相机的y轴位置在Update()方法的计算中没有改变,这将工作,因为它看起来在你的情况下