【问题标题】:Teleporting Character From Edge to Edge of the Screen将角色从屏幕边缘传送到边缘
【发布时间】:2018-03-05 02:52:33
【问题描述】:

我正在尝试将角色从屏幕边缘传送到我正在使用的相反边缘:

var pos: Vector3 = Camera.main.WorldToViewportPoint(transform.position);

       if (pos.x < 0.0) {
           pos = new Vector3(0.0, 0.0, 0.0);
           transform.position = pos;
           //Debug.Log("I am left of the camera's view.");
       }


       if (1.0 < pos.x) {
           pos = new Vector3(0.0, 0.0, 0.0);
           transform.position = pos;
          // Debug.Log("I am right of the camera's view.");
       } 
        if (pos.y < 0.0) Debug.Log("I am below the camera's view.");
        if (1.0 < pos.y) Debug.Log("I am above the camera's view.");

这工作完美,但问题是它将角色传送到中心,当我更改值以使其传送到边缘时,它无法正常工作

【问题讨论】:

  • 这是因为第一行中的pos 被“翻译”到视口空间,但您设置的位置是在世界空间中(0,0,0 是场景的中心),您只需要将新坐标“平移”到“另一个方向”,即从视口到世界空间。
  • @yes 我知道那是中心,当我将值设置到边缘时会发生什么情况它不起作用我到底应该改变什么?
  • 在设置位置之前使用Camera.ViewportToWorldPointdocs.unity3d.com/ScriptReference/…
  • @yes 所以我必须使用 ViewToWorldPoint 而不是 WorldToviewPoint
  • 不,您设置的位置需要在世界空间中。

标签: unity3d unityscript


【解决方案1】:

问题是您将世界坐标 (transform.position) 转换到视口空间,进行一些更改,但在将其应用到 transform.position 之前,切勿从视口空间转换回世界空间。

    //you get a world space coord and transfom it to viewport space.
    Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);

    //everything from here on is in viewport space where 0,0 is the bottom 
    //left of your screen and 1,1 the top right.
    if (pos.x < 0.0f) {
        pos = new Vector3(1.0f, pos.y, pos.z);
    }
    else if (pos.x >= 1.0f) {
        pos = new Vector3(0.0f, pos.y, pos.z);
    }
    if (pos.y < 0.0f) {
        pos = new Vector3(pos.x, 1.0f, pos.z);
    }
    else if (pos.y >= 1.0f) {
        pos = new Vector3(pos.x, 0.0f, pos.z);
    }

    //and here it gets transformed back to world space.
    transform.position = Camera.main.ViewportToWorldPoint(pos);

【讨论】:

  • 我实际上在 Y 轴上遇到了一点麻烦,但除此之外,代码很棒,谢谢✌?✌?✌???
  • @ShamuelSimpsonG。什么麻烦?另外,如果答案有帮助,请将其标记为正确。
  • 准备好了。角色似乎在 Y 轴上上下浮动,但只是有时
  • @ShamuelSimpsonG。嗯,你需要更好地描述一下我不明白你的意思:D
猜你喜欢
  • 1970-01-01
  • 2014-02-09
  • 2016-12-14
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
相关资源
最近更新 更多