簡體   English   中英

C#相機在X軸上跟隨播放器

[英]C# Camera Follow Player on X-axis

我有這樣的問題。 我希望相機僅在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;

    }
}

我可以通過將其附加到相機上以跟隨目標來使用此代碼,但是運動非常糟糕,尤其是在嘗試使目標跳躍時。 我認為這是一個問題,因為相機在目標移動后會變慢一點。 救命!!!

在這種情況下,我建議不要把相機當成小孩,而只寫一個腳本來跟蹤它。 您可以通過這種方式輕松地允許/禁止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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM