简体   繁体   English

Unity:仅当角色到达 Y 轴上的某个点时才使用相机跟踪玩家的移动?

[英]Unity: Track player movement with camera only when character reaches a certain point on the Y axis?

I'm currently working on a 2D platforming game using Unity.我目前正在使用 Unity 开发 2D 平台游戏。 When the player jumps, I prevent the camera from following them in order to allow the player to see what is beneath them.当玩家跳跃时,我会阻止相机跟随他们,以便让玩家看到他们下方的东西。 However, I have a mechanic implemented that allows the player to perform a double jump when they grab an enemy, and this double jump makes the player jump past the boundary of the screen.但是,我实现了一个机制,允许玩家在抓住敌人时执行二段跳,这种二段跳使玩家跳过屏幕边界。 I was wondering how I would go about getting the camera to smoothy follow the player only when they exit certain boundaries.我想知道我将如何让相机仅在玩家退出某些边界时平滑地跟随玩家。 I have basic code written that does this in a choppy way.我编写了基本的代码,以一种断断续续的方式做到这一点。 I will include gifs to show how my game currently behaves, and an example of how I want it to behave.我将包含 gif 来展示我的游戏当前的行为方式,以及我希望它如何表现的示例。

Here is the code I have written in my camera controller:这是我在相机 controller 中编写的代码:

  transform.position = new Vector3(player.position.x, 50, -100);

    if (player.position.y > 50)
    {

        transform.position = player.position - transform.forward * camDist + Vector3.up * playerHeight;

    }

Below is an embeded imgur gif of what my code does now:下面是我的代码现在所做的嵌入 imgur gif:

 <blockquote class="imgur-embed-pub" lang="en" data-id="a/houedOV" data-context="false" ><a href="//imgur.com/a/houedOV"></a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>

and below here is an example of what I am trying to achieve:下面是我要实现的目标的示例:

 <blockquote class="imgur-embed-pub" lang="en" data-id="a/deg5yeq"><a href="//imgur.com/a/deg5yeq"></a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>

You should moving camera from origin to destination instead of set camera to destination immediately (1 frame or 1 update called)您应该将相机从原点移动到目的地,而不是立即将相机设置到目的地(调用 1 帧或 1 次更新)

Try to set camera position with this code尝试使用此代码设置相机 position

void Update(){

   // ...  
   Vector2 destination = Vector2.zero; // your camera destination you expected
   float maxMoveDistance = 1; // maximum distance to move camera in each frame
   camera.transform.position = Vector2.MoveTowards(camera.transform.position, destination, maxMoveDistance); // move camera to destination
        
}

ok, I figured out the answer to my own question!好的,我想出了我自己问题的答案!

It was as simple as this:就这么简单:

 void Update()
{
   

    if (player.position.y > 50)
    {

        
        transform.position = new Vector3(player.position.x, player.position.y, -100);
    }

    else
    {
        transform.position = new Vector3(player.position.x, 50, -100);

    }

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

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