首页 > 解决方案 > 当玩家在 Unity2D 中使用 Cinemachine 跳跃时,如何让凸轮忽略 y 轴?

问题描述

美好的一天,我正在制作一款 2D 平台游戏,并且正在尝试让玩家跟随玩家。但是忽略 y 轴,因此当玩家跳跃时,凸轮会停留在原位而不是跟随玩家。

示例(参见资产包演示):https ://ansimuz.itch.io/gothicvania-church-pack

如何使用 Cinemachine 做到这一点?

标签: c#unity3d2dgame-engine

解决方案


您不必在相机控制器脚本中覆盖相机的 Y 值。这将是一个非常基本的实现:

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

public GameObject player;        //Public variable to store a reference to the player game object
public bool followY = false;

private Vector3 offset;            //Private variable to store the offset distance between the player and camera

// Use this for initialization
    void Start () 
    {
        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }

// LateUpdate is called after Update each frame
    void LateUpdate () 
    {
        // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
        if(followY)
          {
          transform.position = player.transform.position + offset; // we should follow the player Y movements, so we copy the entire position vector
          }
        else
          {
          transform.position = new Vector3(player.transform.position.x, transform.position.y, player.transform.position.z) + offset; // we just copy the X and Z values
          }
    }
}

将此脚本附加到相机,您可以通过相应地设置布尔值来启用或禁用 Y 轴移动。如果您永远不需要此功能,只需将该行保留在 else 块中。

我希望这能帮到您!


推荐阅读