user2246120
user2246120

Reputation: 1515

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(). 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:

 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. I need to access the camera to find the y position:

 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);
        }
    }
}

Upvotes: 1

Views: 1763

Answers (1)

Daahrien
Daahrien

Reputation: 10320

If you need the worldrendered cam in other classes. 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.

In here you are creating a new Vector every frame,which will make the garbage collector very sad. Don't do it.

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

Upvotes: 3

Related Questions