Created
August 1, 2014 15:14
-
-
Save jnsdbr/7f349c6a8e7f32a63f21 to your computer and use it in GitHub Desktop.
Rotating a sprite towards the mouse pointer in phaser.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.onload = function() | |
{ | |
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '', { | |
preload: preload, | |
create: create, | |
update: update | |
}); | |
var dragging = false; | |
function preload () | |
{ | |
game.input.maxPointers = 1; | |
game.load.image('logo', 'phaser.png'); | |
} | |
function create () | |
{ | |
logo = game.add.sprite(game.world.centerX, game.world.centerY, 'logo'); | |
logo.anchor.setTo(0.5, 0.5); | |
} | |
function update() | |
{ | |
var targetAngle = (360 / (2 * Math.PI)) * game.math.angleBetween( | |
logo.x, logo.y, | |
this.game.input.activePointer.x, this.game.input.activePointer.y) + 90; | |
if(targetAngle < 0) | |
targetAngle += 360; | |
if(game.input.activePointer.isDown && !dragging) | |
{ | |
dragging = true; | |
} | |
if(!game.input.activePointer.isDown && dragging) | |
{ | |
dragging = false; | |
} | |
if(dragging) | |
{ | |
logo.angle = targetAngle; | |
} | |
} | |
}; |
You can also rotate it in this way ( without 'dragging' variable ), just pass the game and the desired sprite, image etc, to the function
updateAngle(game, view) { const dx = game.input.activePointer.x - view.x; const dy = game.input.activePointer.y - view.y; const targetAngle = (360 / (2 * Math.PI)) * Math.atan2(dy, dx); view.angle = targetAngle; }
function update() { // passing this.game and for example some image like this._img updateAngle(this.game, this._img); }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Incredibly easy. Well played