简体   繁体   English

libgdx:使用相机测试屏幕外是否有对象

[英]libgdx: using camera to test if object out of screen

I followed this example to create an object pool of snowflakes. 我按照这个例子创建了一个雪花对象池。 It gets released when it's out of screen. 当它离开屏幕时它会被释放。 My problem is that I don't have access to the WorldRenderer's camera in order to use: pointInFrustrum(). 我的问题是我无法访问WorldRenderer的相机以便使用:pointInFrustrum()。 I worked around that by making the camera static. 我通过使相机静止来解决这个问题。 Is there another way of finding out if the the snowflake is out of screen or to get the current positon of the camera? 还有另一种方法可以找出雪花是否在屏幕之外或者是否能够获得相机的当前位置? It just seems that this isn't a good solution. 这似乎不是一个好的解决方案。

Snowflake.java: Snowflake.java:

 public void update (float delta){

    // update snowflake position
    position.add(0, -1*delta*5);

    // if snowflake is out of screen, set it to dead
    if(!WorldRenderer.cam.frustum.pointInFrustum(new Vector3(position.x, position.y, 0))) {
        alive = false;
    }
}

The same problem in World's update method. World的更新方法中存在同样的问题。 I need to access the camera to find the y position: 我需要访问相机才能找到y位置:

 private void updateSnowflakes(float deltaTime) {
    spawnTime += deltaTime;
    if(spawnTime > spawnDelay) {
        spawnTime = 0;
        Snowflake item = snowflakePool.obtain();
        float x = rand.nextFloat() * Helper.FRUSTUM_WIDTH;
        float y = WorldRenderer.cam.position.y + Helper.FRUSTUM_HEIGHT/2;
        item.init(x, y);
        activesSnowflakes.add(item);
    }

    int len = activesSnowflakes.size;
    for (int i = len; --i >= 0;) {
        Snowflake item = activesSnowflakes.get(i);
        if (item.alive == false) {
            activesSnowflakes.removeIndex(i);
            snowflakePool.free(item);
        } else {
            item.update(deltaTime);
        }
    }
}

If you need the worldrendered cam in other classes. 如果你需要其他类中的worldrendered cam。 You would need to send it as a parameter. 您需要将其作为参数发送。 your approach is not bad either. 你的方法也不错。 Just dont forget to initialize the static camera in the WorldRendered constructor because it may survive from previous runs. 只是不要忘记在WorldRendered构造函数中初始化静态相机,因为它可能在以前的运行中存活。

In here you are creating a new Vector every frame,which will make the garbage collector very sad. 在这里,你每帧都会创建一个新的Vector,这会让垃圾收集器非常难过。 Don't do it. 不要这样做。

if(!WorldRenderer.cam.frustum.pointInFrustum(new Vector3(position.x, position.y, 0))) {

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

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