如何使相机跟随角色而不在Unity中的屏幕空间相机渲染模式中拖动背景?

时间:2018-02-04 17:59:17

标签: unity3d unity5

我正在制作2D平台,我在画布中使用屏幕空间相机渲染模式。现在背景完美地适合每个宽高比的屏幕内部。但是当我让相机跟随角色时,背景也伴随着它,使角色看起来不动。

玩家移动代码:

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);
    }
}

1 个答案:

答案 0 :(得分:2)

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