首页 文章

在unity2d中移动物体,它的孩子不在相机中

提问于
浏览
0

我和一些儿童游戏对象一起制作了一个游戏对象,以表示在特定情况发生时显示的信息 .

我已经调整了信息游戏对象(连同它的'孩子们)在相机区的位置 . 问题是我想把游戏对象(和它的'孩子一起)移出相机,可能在顶部或左边 . 以下是展示我想要的位置的划痕:

enter image description here

因此,我可以在需要的时候移动信息游戏对象及其“儿童(红盒子)”,并且有一些移动效果,我可以将其移回但是在游戏开始时可以找到一种优雅的方式将其移出相机 .

主要是因为我不知道如何计算出相机的位置 . 也许找到相机的上边框和游戏对象及其孩子的大小?

我知道我可以通过添加一个标记游戏对象来表示信息游戏对象的下行边界,并将其移动直到它不可见,但是有更优雅的方式吗?

有任何想法吗?

2 回答

  • 0

    对于这个,我将使用以下技巧:使用任何方法(动画,协同程序,更新方法......)以您希望的方式将项目移出屏幕 . 然后你可以使用OnBecameInvisible事件,当不再需要在任何相机上渲染项目时调用该事件 . 该事件将用于检测父对象移出屏幕,并且您想要停止当前移动 . 然后,您只需要在此事件中定义您要停止当前的移动行为,您将完成 .

    void OnBecameInvisible() {
        // Stop moving coroutine, moving in Update or current animation.
    }
    

    正如你所说,可能有更优雅的方式,但我认为这种方法应该足以达到你想要达到的目的 .

  • 0

    我花了很多时间,但是我找到了这种方式,将这个脚本附加到你的gameObject:

    public Renderer rend;
    //drag the camera to the script in the inspector
    public Camera camera1;
    Vector3 bottomleft;
    Vector3 topright;
    
    void Start()
    {
        rend = GetComponent<Renderer>();
        //the top-right point of the camera bounds
        topright= camera1.ViewportToWorldPoint(new Vector3(0, 0, transform.position.z));
        //the bottom-left point of the camera bounds
        bottomleft = camera1.ViewportToWorldPoint(new Vector3(1, 1, transform.position.z));
    
        StartCoroutine(MoveUp());
    
    }
    IEnumerator MoveUp()
    {
        //while the position and the height are lower that the Y of top right
        while (transform.position.y + rend.bounds.size.y < topright.y)
        {
            //move the object to the new position (move it up)
            transform.position = new Vector3(transform.position.x, transform.position.y + .01f, transform.position.z);
            //and wait for 1/100 of a second 
            yield return new WaitForSecondsRealtime(.001f);
        }
    }
    

    你可以使用WaitForSecondsRealtime值来改变移动的速度 .

相关问题