Jump to content

Incremental sprite rotation based on mouse position.


symof
 Share

Recommended Posts

var game = new Phaser.Game(1024, 600, Phaser.auto, 'phaser-example', { preload: preload, create: create, update: update, render: render });

var result = 'Press a key';

function preload() {
	//load assets
    game.load.image("single_turret","./img/single_turret_64x64.png");
    game.load.image("mouse","./img/mouse.png");
}

function create() {
	//start physics
	game.physics.startSystem(Phaser.Physics.P2JS);
	
	single_turret = game.add.sprite(400,300,'single_turret');
	mousep = game.add.sprite(50,50,'mouse');

	
	//enable psysics on all items and enable debugged
	game.physics.p2.enable([single_turret,mousep], true);

	mousep.body.setCircle(4);
	mousep.body.kinematic = true;
	
	single_turret.body.setCircle(4);
	single_turret.body.kinematic = true;	

}

function update() { 
}

function render(){
	game.debug.text(result, 32, 32);
	
	mousep.body.x = game.input.x;
	mousep.body.y = game.input.y;

	lookAtObject(single_turret, mousep, 0.005);
}

function lookAtObject(obj, target, rotspeed){
	var angle = Math.atan2(target.body.y - obj.body.y, target.body.x - obj.body.x);
	result = obj.body.rotation + '**'+ (angle + game.math.degToRad(90))+ '**'+obj.body.angle;
	obj.body.rotation = angle + game.math.degToRad(90);
     
}

The code above rotates the "turret" to always be pointed towards the mouse so that it can fire at the mouse position.

The code works, but I want to add a rotation speed to it, however I can't figure out how to code that in. The lookAtObject() function is where I have the problem.

function lookAtObject(obj, target, rotspeed){
	var angle = Math.atan2(target.body.y - obj.body.y, target.body.x - obj.body.x);
	result = obj.body.rotation + '**'+ (angle + game.math.degToRad(90))+ '**'+obj.body.angle;
    
	if (obj.body.rotation <= angle + game.math.degToRad(90)){
		obj.body.rotation += rotspeed;
	}else{
		obj.body.rotation -= rotspeed;
	}
}

This statement does not work as intended because of how p2js works, so when It gets at ( -x , 0) the radians go from -1.5 to 4.7 and the rotation will reverse.

I am really stumped atm, so any ideas on how to approach this?

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...