【发布时间】:2016-10-16 07:04:12
【问题描述】:
我现在正在使用 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;
【问题讨论】:
-
我会向玩家添加一个子游戏对象并将其设置到所需位置,然后将其用作相机目标。
-
完成,再次感谢您!
-
这个问题是关于c#,而不是unityscript