Skip to content

Instantly share code, notes, and snippets.

@jnsdbr
Created August 1, 2014 15:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jnsdbr/7f349c6a8e7f32a63f21 to your computer and use it in GitHub Desktop.
Save jnsdbr/7f349c6a8e7f32a63f21 to your computer and use it in GitHub Desktop.
Rotating a sprite towards the mouse pointer in phaser.js
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;
}
}
};
@WhatNot911
Copy link

Incredibly easy. Well played

@davit-badalyan
Copy link

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