【问题标题】:2D game platform camera goes up when player touches edges玩家触摸边缘时 2D 游戏平台摄像头会升起
【发布时间】:2015-11-09 14:16:46
【问题描述】:

我正在做一个 2D 平台游戏,玩家只能攀爬(y 轴)。 我正在尝试做的是,当我接近顶部边缘时,我的相机会上升一点,这样我就可以看到更多的关卡。

我有这个,但它不工作:

Public Transform player;

     Void Start() { }
     Void Update() 
     {

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

     }  

Other Way is like this 但不工作不止一次,我可能需要设置 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;
    }
}

}

【问题讨论】:

  • 你只检查player.transform.position,应该是player.transform.position.y &gt; Screen.height - 50
  • PublicVoid 应为小写。
  • 仍然无法正常工作,是的,我知道,但我只是在这里手工制作的 =P

标签: c# android unity3d 2d


【解决方案1】:

你在这里比较两个不同的东西。 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);

最后,请务必发布您在提问时遇到的错误,解释您预期会发生什么以及实际发生什么。

【讨论】:

    【解决方案2】:

    您可以尝试调整职位之间的关系,例如。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多