[SOLVED] Changing the hitbox for a group by using setSize. And setting the individual velocities of an object in a group

I have: bullets = this.physics.add.group();

I also have a ship and I was able to change the ship’s hitbox using .setSize(). Now If I understand groups they seem to define a uniform format for what ever game object the group creates? In my game when the bullets come out they have massive hit boxes. Not sure how to change them as theres no .setSize() for groups.

Edit: Also for a game like asteroids is it even recommended for the bullets to be in a group? Seems like my bullets aren’t independent of each other which means I cant give them independent directions.

You can’t do this through the group config but you can do, e.g.,

bullets.children.iterateLocal('setSize', width, height, center);

Ah thanks, but I realized perhaps a group is not what I want? When I shoot a bunch of bullets in one direction they get sent out, but if I turn around and shoot they will all shift direction and move in the new direction Possibly because of the way I have the code here?
function shoot(){ bullets.create(ship.x, 290, 'bullet'); bullets.setVelocityX(Math.cos(ship.rotation) * 300); bullets.setVelocityY(Math.sin(ship.rotation) * 300); }

A Group is simply a list of Game Objects (and in the case of a Physics Group, a list of physics-enabled Game Objects). They are fully independent, but the Group provides methods which allow you to operate on all of them at once. Calling setVelocityX or setVelocityY on a Physics Group will set the velocity of all of the Game Objects in it. In the code you posted, you first create a new bullet (bullets.create), then call the setter methods on the entire Group (bullets.setVelocityX / Y), which changes all of the bullets.

The create method of a Group will return the Game Object which was created. You can either operate on it directly or store it in a variable and operate on it, which allows you to change just that Game Object:

function shoot(){
    var bullet = bullets.create(ship.x, 290, 'bullet');
    bullet.setVelocity(Math.cos(ship.rotation) * 300, Math.sin(ship.rotation) * 300);
}

This example assumes you haven’t changed the Group’s classType (if you have, the Game Objects might not have the setVelocity method on them). The single setVelocity call will set both the X and the Y velocity at once, so it’s a little shorter. As I mentioned earlier, note that you can also skip the intermediate variable:

function shoot(){
    bullets.create(ship.x, 290, 'bullet').setVelocity(Math.cos(ship.rotation) * 300, Math.sin(ship.rotation) * 300);
}

In both cases, you call the setVelocity method on the Game Object returned by bullets.create, not on the entire Group.

3 Likes