Search code examples
arraysobjectlibgdx

LibGdx object array


I have created an array of objects in my libGdx project like this:

Array<Bird> birds = new Array<Bird>();

Here Bird is one object class.

I want to draw 10 Bird objects one by one on the screen.So I did like this.

private void MakeBird() {

    Bird b = objectFactory.createBird();

    for (int i = 0; i < 10; i++) {
        birds.add(b);

    }

}

createBird method of objectFactory:

public Bird createBird() {
    Bird bird = new Bird();
    bird.setPosition(0,0);
    return bird;
}

Here I want only 10 objects.But when I try to print the array size,it is incrementing continuousely.How can I implement this properly? I also want to know how to draw these array objects using spriteBatch. It will be very helpful if I get an explanation with code.


Solution

  • In order to keep the size of the birds array constant you need to modify your MakeBird() function into this

    private void MakeBird() {
        int birdsToAdd = 10 - birds.length;
        for (int i = 0; i < birdsToAdd ; i++) {
            birds.add(objectFactory.createBird());
        }
    }
    

    Your version of MakeBird() would simply add the same object ten times into the birds array. So, why is this bad? Because Java objects are reference type, meaning that if you modify one object all the references to that object will also change. In your case, if you change the position of one bird in the array, all the birds position will change. I don't know if this is intentional. But if you want to add different Bird objects then you should use the MakeBird() function like I implemented above. Nice catch there by marius.

    As for your second query about how to render these objects to the screen, what you can do is, update your Bird class to contain a render or a draw method (you can name the method whatever you want) and in your main class you should update your render method to call the render/draw method of the Bird class. You can do this as such

    //Bird class
    class Bird {
        //Your data members
        //Your member functions
    
        public void draw(SpriteBatch batch) {
            batch.draw(some_bird_image, bird_x_position, bird_y_position);
        }
    }
    
    //Render method in main class
    public void render() {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 
        batch.begin();
        for(Bird bird : birds) {
            bird.draw(batch);
        }
        batch.end();
    }