Phaser Hover Example
by Trev Burley
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.6.2/phaser.min.js"></script>
CSS
body {
margin: 0;
padding: 0;
}
JavaScript
var gameWidth = window.innerWidth;
var gameHeight = window.innerHeight;
var game = new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, '', {
preload: preload,
create: create,
update: update
});
function preload() {
// No allowed on JSFiddle with Phaser
// game.load.image('targetSprite', 'https://s3.postimg.org/ds2x9uakv/target.png');
// game.load.image('draggableSprite', 'https://s3.postimg.org/tp1p6k2z3/draggable.png');
}
function create() {
// ****** HACK TO SHOW OBJECT ON JSFIDDLE *********
var width = 150;
var height = 150;
var targetRect = game.add.bitmapData(width, height);
targetRect.ctx.beginPath();
targetRect.ctx.rect(0, 0, width, height);
targetRect.ctx.fillStyle = '#ffffff';
targetRect.ctx.fill();
var draggableRect = game.add.bitmapData(width - 50, height - 50);
draggableRect.ctx.beginPath();
draggableRect.ctx.rect(0, 0, width - 50, height - 50);
draggableRect.ctx.fillStyle = '#ff0000';
draggableRect.ctx.fill();
// ****** END HACK *********
game.stage.backgroundColor = "#cccccc";
var rows = Math.floor(Math.random() * 3) + 1;
var rowHeight = gameHeight / rows;
// Place some semi-random target sprites in the scene
for (var i = 0; i < rows; i++) {
var rowCount = Math.floor(Math.random() * 4) + 1;
var targetSpacing = (gameWidth - 300) / rowCount;
for (var w = 0; w < rowCount; w++) {
var y_pos = (rowHeight * w) + (rowHeight / 2);
var x_pos = targetSpacing * (w + 1);
var sprite = game.add.sprite(x_pos, y_pos, targetRect);
sprite.anchor.setTo(0.5);
sprite.scale.setTo(0.5);
sprite["target_custom_id"] = "a_specific_id_" + w; // This ID is important and will need to be reported on hover of the draggable
}
}
var draggable = game.add.sprite(game.world.centerX, game.world.centerY, draggableRect);
draggable.anchor.setTo(0.5);
draggable.scale.setTo(0.5);
draggable['draggable_custom_id'] = "another_specific_id"; // There will be multiple...