issey Posted November 30, 2016 Share Posted November 30, 2016 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.enableDrag(); 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? Thanks! Link to comment Share on other sites More sharing options...
samme Posted November 30, 2016 Share Posted November 30, 2016 Think you can do var roomBounds = Phaser.Rectangle.clone(room); // … starGroup.create(roomBounds.randomX, roomBounds.randomY, 'star'); var roomBounds = room.getBounds(); will also work but is likely slower. issey 1 Link to comment Share on other sites More sharing options...
issey Posted December 1, 2016 Author Share Posted December 1, 2016 Thanks!! I get how it works now! Link to comment Share on other sites More sharing options...
samme Posted December 9, 2016 Share Posted December 9, 2016 Be careful (since I’ve made this mistake): Phaser.Rectangle.clone(sprite); 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 More sharing options...
Recommended Posts