以下是相机跟随的代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraTracker : 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;
[SerializeField]
private float xMax;
[SerializeField]
private float yMax;
[SerializeField]
private float xMin;
[SerializeField]
private float yMin;
// Use this for initialization
private void Start()
{
target = GameObject.Find ("Player").transform;
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;
}
void LateUpdate()
{
transform.position = new Vector3(Mathf.Clamp(target.position.x,xMin,xMax), Mathf.Clamp(target.position.y,yMin,yMax), transform.position.z);
}
}
你如何让yMax没有钳位? 另外,如何使yMin等于相机底部的位置,以便在相机向上移动时最小高度发生变化?
由于
答案 0 :(得分:0)
你如何让yMax没有钳位?
如果您不想约束Y的最大值,请使用Mathf.Max
代替Mathf.Clamp
:
Mathf.Max(target.position.y,yMin)
另外,如何让yMin等于相机底部的位置,以便在相机向上移动时最小高度发生变化?
yMin = Camera.main.transform.position.y;
因此,您生成的LateUpdate
方法将是:
void LateUpdate()
{
yMin = Camera.main.transform.position.y;
transform.position =
new Vector3(Mathf.Clamp(target.position.x,xMin,xMax),
Mathf.Max(target.position.y, yMin), transform.position.z);
}