Search code examples
libgdxbox2dparticles

Libgdx and Box2d / Particles are not following bodies


i'll just cut to the chase. So i'm making this game where you should kill other objects with your spells i've created bullets and their bodies we're all good it's working. But i wanted to make it look special and "magiclike" so i decided to use particles. I've made the particles and put and made them follow the bullet bodies with this code:

 for (Bullet bullet : bullets) {
            bullet.update(dt);
            if (!bullet.destroyed){
                fireFx.start();
                fireFx.setPosition(bullet.getPosition().x, bullet.getPosition().y);
                fireFx.update(dt);
            }
        }

but there's a problem when i fire multiple bullets particles are just dissappearing from the all of the first bullets i fired and just appears on the last one. Can someone lead me on this one please ?

-----------------EDIT-----------------

Now i've got another problem that when bullet collides with something it gets destroyed and render method stops working but i want it to keep rendering till the animation is over. Like i don't want them to disappear suddenly here is my code for this:

for(int i = 0; i<bullets.size; i++){
        if(!bullets.get(i).destroyed && !bullets.get(i).fireFx.isComplete()) 
                bullets.get(i).fireFx.draw(game.batch);
    }

fireFx.isComplete() is not working correctly what is the reason ?


Solution

  • The issue is that you're updating a single particle to have the coordinates of all the bullets in a list, and effectively keeping the coordinates of the last bullet in the list. You could maintain a Map that maps Bullets onto Particles, but I would instantiate a fireFx object when a Bullet is created and add it to the Bullet object. Then, in the Bullet#update method you can call the particle update method:

    public void update(float dt) {
        [...]
        if ( !this.isDestroyed()) {
            [...]
            this.fireFx.start();
            this.fireFx.setPosition(this.getPosition().x, this.getPosition().y);
            this.fireFx.update(dt);
            [...]
        }
        [...]
    }