简体   繁体   English

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

[英]Follow Player By Camera in 2D games

I used This code for my MainCamera for following the player in my 2d game in Unity5 : 我使用该代码为我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);
        }

    }
}

It work fine But player is in middle of screen allways . 它工作正常,但播放器始终处于屏幕中间。 i wan player be in down of screen and my sprite for show Earth of my game will stick below the camera . 我希望玩家进入屏幕下方,我的用来展示我的游戏地球的精灵将停留在摄像机下方。 i mean better in following pictures: 我的意思是以下图片更好:

What I Want : 我想要的是 :

在此处输入图片说明

The Result : 结果 :

在此处输入图片说明

You can add a vertical offset to the calculation. 您可以向计算添加垂直偏移。 Just adding it to destination should do that I think. 我认为,只需将其添加到destination

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

Otherwise you could also add an empty gameobject to the player gameobject and use that as your target. 否则,您也可以将一个空的游戏对象添加到玩家的游戏对象并将其用作目标。

One thing that you might need to consider is the resolution. 您可能需要考虑的一件事是分辨率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM