JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.0.3/phaser.min.js"></script>
JavaScript
//= require ./libs
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update });
function preload() {
game.load.image('somesprite','http://examples.phaser.io/assets/sprites/phaser.png');
}
var sprite;
var cursors;
function create() {
// Enable p2 physics
game.physics.startSystem(Phaser.Physics.P2JS);
game.physics.p2.gravity.y = 1
// Add a sprite
sprite = game.add.sprite(200, 200, 'somesprite');
sprite.anchor.set(0.5,0)
// Enable if for physics. This creates a default rectangular body.
game.physics.p2.enable(sprite, true);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
//1. angleToPointer makes no assumption over our current angle- th thinks it's always 0
//2. so include the current rotation of our sprite in the expression
//3. subtract Math.PI/2 as the angle of atan2 (which is sued by angleToPointer) is rotated by 90deg (this is Math.PI/2)
//Result: Now we have a delta value that if applied directly to rotation would yield
//in a value so that the sprites top center points to the mouse.
deltaMouseRad = sprite.rotation - game.physics.arcade.angleToPointer(sprite) - Math.PI/2;
//don't be confused. I want the P of 'Phaser' to point to the mouse so rotate it again by -90deg
deltaMouseRad = deltaMouseRad - Math.PI/2
mod = Math.PI * 2
//modulo on float, works in js, means: clamp value to [-Math.PI*2,Math.PI*2]
deltaMouseRad = deltaMouseRad % mod;
//lets call it phase shift, angle would jump, lets fix it
if (deltaMouseRad != deltaMouseRad % (mod/2) ) {
deltaMouseRad = (deltaMouseRad < 0) ? deltaMouseRad + mod : deltaMouseRad - mod;
}
//speed is some factor to get the object faster to the target rotation.
//remember we are wotking with the angle velocity and let the engine
//rotate the body
speed = 150
sprite.body.rotateLeft(speed * deltaMouseRad);
}
function updateSimple(){
...