如何在 Unity 的屏幕 space 相机渲染模式下让相机跟随角色而不拖动背景?

How to make the camera follow the character without dragging the background along with it in screen space camera render mode in Unity?

我正在制作一个 2D 平台,我在 canvas 中使用屏幕 space-相机渲染模式。现在,背景在每个宽高比下都完美地适合屏幕。但是当我让相机跟着人物走的时候,背景也随之而来,让人物看起来像不动了。

玩家移动代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    private Rigidbody2D myRigidbody;

    [SerializeField]
    private float movementSpeed;

    // Use this for initialization
    void Start () 
    {
        myRigidbody = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void FixedUpdate () 
    {
        float horizontal = Input.GetAxis ("Horizontal");
        HandleMovement(horizontal);
    }

    private void HandleMovement(float horizontal)
    {
        myRigidbody.velocity = new Vector2 (horizontal * movementSpeed, myRigidbody.velocity.y);
    }
}

相机跟随代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour 
{
    public Transform target; 
    Vector3 velocity = Vector3.zero;

    public float smoothTime = 0.15f;

    public bool YMaxEnabled = false;
    public float YMaxValue = 0;
    public bool YMinEnabled = false;
    public float YMinValue = 0;

    public bool XMaxEnabled = false;
    public float XMaxValue = 0;
    public bool XMinEnabled = false;
    public float XMinValue = 0;

    void FixedUpdate()
    {

        Vector3 targetPos = target.position;

        //vertical
        if (YMinEnabled && YMaxEnabled)
        {
            targetPos.y = Mathf.Clamp (target.position.y, YMinValue, YMaxValue);
        } 
        else if (YMinEnabled) 
        {
            targetPos.y = Mathf.Clamp (target.position.y, YMinValue, target.position.y);
        }
        else if (YMaxEnabled) 
        {
            targetPos.y = Mathf.Clamp (target.position.y, target.position.y, YMaxValue);
        }

        //horizontal
        if (XMinEnabled && XMaxEnabled)
        {
            targetPos.x = Mathf.Clamp (target.position.x, XMinValue, XMaxValue);
        }
            else if (YMinEnabled)
        {
            targetPos.x = Mathf.Clamp (target.position.x, XMinValue, target.position.x);
        }
            else if (YMaxEnabled)
        {
            targetPos.x = Mathf.Clamp (target.position.x, target.position.x, XMaxValue);
        }


        targetPos.z = transform.position.z;

        transform.position = Vector3.SmoothDamp (transform.position, targetPos, ref velocity, smoothTime);
    }
}

如果您使用屏幕 space 摄像头,则 Canvas 将随摄像头一起移动。我建议使用 Sprite Renderer 而不是 Canvas 面板作为关卡背景。如果您需要根据屏幕缩放 Sprite,请从代码中执行。此外,要滚动背景,您可以按照本教程进行操作: https://unity3d.com/learn/tutorials/topics/2d-game-creation/2d-scrolling-backgrounds