当玩家触摸边缘时,2D 游戏平台相机会升起

2D game platform camera goes up when player touches edges

我正在做一款 2D 平台游戏,玩家只能在其中攀爬(y 轴)。 我想要做的是,当我到达顶部边缘附近时,我的相机会上升一点,这样我就可以看到更多的水平。

我有这个,但它不起作用:

Public Transform player;

     Void Start() { }
     Void Update() 
     {

         if (player.transform.position > Screen.height - 50)
         {
            transform.position.y += speed * Time.deltaTime; 
         }

     }  

其他方法是这样的但是工作不止一次,我可能需要设置 move = false;但不知道如何不中断 Lerp:

float moveTime = 1f; // In seconds
float moveTimer = 0.0f; // Used for keeping track of time

bool moving = false; // Flag letting us know if we're moving

public float heightChange = 7.0f; // This is the delta

// These will be assigned when a collision occurs
Vector3 target; // our target position
Vector3 startPos; // our starting position


void Start()
{

}


void Update()
{

    // If we're currently moving and the movement hasn't finished
    if (moving && moveTimer < moveTime)
    {
        // Accumulate the frame time, making the timer tick up
        moveTimer += Time.deltaTime;


        // calculate our ratio ("t")
        float t = moveTimer / moveTime;

        transform.position = Vector3.Lerp(startPos, target, t);

    }
    else
    {
        // We either haven't started moving, or have finished moving
    }

}

void OnTriggerEnter2D(Collider2D other)
{
    if (!moving)
    {
        // We set the target to be ten units above our current position
        target = transform.position + Vector3.up * heightChange;

        // And save our start position (because our actual position will be changing)
        startPos = transform.position;

        // Set the flag so that the movement starts
        moving = true;
    }
}

}

您可以尝试在位置之间进行 lerping,例如

transform.position = new trasform.lerp(transform.position, player.transform.position, speed*Time.DeltaTime);

只需使用 if 语句触发一个 bool,然后执行 lerp,这样摄像机就会移动到您需要的位置,而不仅仅是当玩家击中某个点时。然后当相机完成移动时,重置 bool 准备下一次

你在这里比较两个不同的东西。 Screen.height 以像素为单位,而玩家位置以世界单位为单位。因此,假设您的屏幕是 1024x768,您正在检查您的播放器是否高于 718,这在世界单位中是一个巨大的数量。

您需要做的是将一个单位转换为另一个单位,然后与 http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

进行比较

我注意到的另一件事是这个脚本被命名为播放器,所以我假设这是在控制你的播放器对象,在这种情况下

transform.position.y += speed * Time.deltaTime; 

只会改变你的球员位置。要更改主摄像头的位置,您可以使用:

Camera.main.transform.position += new Vector3(0f, speed * Time.deltaTime, 0f);

最后,总是 post 你在提问时遇到的错误,解释你期望发生的事情和实际发生的事情。