在2D游戏中跟随玩家相机

时间:2016-08-29 11:19:30

标签: c# unity3d

我在 MainCamera 中使用此代码跟踪Unity5中我的2D游戏中的播放器

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

    public float dampTime = 0.15f;
    private Vector3 velocity = Vector3.zero;
    public Transform target;

    // Update is called once per frame
    void Update () 
    {
        if (target)
        {
            Vector3 point = GetComponent<Camera>().WorldToViewportPoint(target.position);
            Vector3 delta = target.position - GetComponent<Camera>().ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
            Vector3 destination = transform.position + delta;
            transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
        }

    }
}

工作正常但是玩家总是在屏幕中间。我想玩家在屏幕下方,我的精灵用于显示我的游戏地球将会粘在相机下方。我的意思是更好地照片:

我想要的:

enter image description here

结果:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以为计算添加垂直偏移。只需将其添加到destination,我就应该这样做。

Vector3 destination = ...
destination.y += someOffset;
transform.position = Vector3.SmoothDamp(...);

否则你也可以在玩家游戏对象中添加一个空的游戏对象并将其作为目标。

您可能需要考虑的一件事是解决方案。