Jump to content

Help with Bounds and Groups


Recommended Posts

Hi everyone!

I'm looking to have sprites generated randomly within another sprite's bounds. I've seen examples of bounds used within sprites, like so for example (from this Phaser example):

    //  Our sprite that will act as the drag bounds
    bounds = game.add.sprite(game.world.centerX, game.world.centerY, 'pic');

    //  And the sprite we'll drag
    sprite = game.add.sprite(300, 300, 'atari');
    sprite.inputEnabled = true;

    sprite.input.boundsSprite = bounds;

However, I haven't seen this applied on a group of random sprites? And when I try this method on my group, it doesn't seem to work.


Here is my code so far...

I'm attempting to have the stars sprites randomly created within the room's image bounds.

var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {
  game.load.image('star', 'assets/images/star.png');
  game.load.image('room', 'assets/images/room.png');

function create() {
  //*** The image I'd like to use for bounds
  room = game.add.image(210, 232, 'room')

  // Create random Star group
  starGroup = game.add.group();

  //  And add 3 sprites to it
  //** I'd like to have these sprites generated within the room's bounds only
  for (var i = 0; i < 3; i++)
  { starGroup.create(game.world.randomX, game.world.randomY, 'star'); }

Any help? 



Link to comment
Share on other sites

Be careful (since I’ve made this mistake):


is accurate only for sprites with anchor (0, 0) (where [x, y] == [left, top]). Otherwise I use

Phaser.Rectangle.cloneFromBounds = function(obj, output) {
  if (output == null) {
    output = new Phaser.Rectangle;
  return output.setTo(obj.left, obj.top, obj.width, obj.height);


Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...