我有这样的问题。我希望相机只在x轴上跟随玩家。最简单的方法是为目标创建MainCamera子级。这是一种相当简单的方法,使得运动不会在某些火山爆发或颤抖的情况下运动得相当顺利。问题是我现在想让MainCamera只跟随x轴。我不知道怎么做这个条件。 下面你将看到我编写的代码,但是当MainCamera是目标的子代码时,此代码不起作用。
/// <summary>
/// Follows to given target on specified axis
/// </summary>
public class FollowerCam : MonoBehaviour
{
public Transform target;
public bool followOnY = false;
public bool followOnX = false;
public bool constrainedOnX = false;
public bool constrainedOnY = false;
public float minY = 0f;
public float maxY = 0f;
public float minX = 0f;
public float maxX = 0f;
[ReadOnly]
public Vector3 offset;
private Vector3 originalPosition;
private void Start()
{
originalPosition = transform.position;
offset = transform.position - target.position;
}
private void Update()
{
if ((!followOnX && !followOnY) || target==null)
return;
transform.position = target.position + offset;
Vector3 normalizedPosition = transform.position;
if (followOnX)
{
if (constrainedOnX)
{
normalizedPosition.x = Mathf.Clamp(normalizedPosition.x, minX, maxX);
}
}
else
normalizedPosition.x = originalPosition.x;
if (followOnY)
{
if (constrainedOnY)
{
normalizedPosition.y = Mathf.Clamp(normalizedPosition.y, minY, maxY);
}
}
else
normalizedPosition.y = originalPosition.y;
normalizedPosition.z = originalPosition.z;
transform.position = normalizedPosition;
}
}
我可以通过将此代码附加到相机以跟随目标来使用此代码,但运动非常糟糕,尤其是在尝试进行目标跳跃时。我认为这是一个问题,因为相机在目标后变慢了一点。帮助!
答案 0 :(得分:2)
在这种情况下,我建议不要让相机作为一个孩子,只需编写一个脚本来让它跟踪。您可以通过这种方式轻松允许/禁止y移动,并在您需要时为您提供更多自由移动摄像机。
public GameObject player; //assign player gameobject to variable in the inspector
public bool lockY = true;
private Vector3 offset;
private Vector3 tempVect;
void Start()
{
offset = transform.position - player.transform.position; //store initial camera offset.
}
void LateUpdate()
{
tempVect = player.transform.position + offset;
if (lockY) // toggle this to allow or disallow y-axis tracking
tempVect.y -= player.transform.position.y; // remove y component of player position
transform.position = tempVect;
}