Something that has been very useful for me lately is to be able to get the angle between two objects or get the angle between the mouse and a central character. For example in a game with a spaceship where you want to click and fire, you need to know the angle to be able to turn the ship. The actual math to get the angle is a bit complex, and I won’t pretend I understand it, but it has been a very useful snippet for me to have.<\/p>\n
getAngle: function(obj1, obj2) {\r\n\/\/ angle in radians\r\nvar angleRadians = Math.atan2(obj2.y - obj1.y, obj2.x - obj1.x);\r\n\/\/ angle in degrees\r\nvar angleDeg = (Math.atan2(obj2.y - obj1.y, obj2.x - obj1.x) * 180 \/ Math.PI);\r\nreturn angleDeg;\r\n},<\/pre>\nAll you need to do to get the angle is to pass two objects like this
\nvar angle=this.getAngle(goodGuy,monster);<\/p>\nHere is an example where I use the angle between the mouse and a space ship to turn the ship.
\nClick anywhere to have the ship point at the mouse.<\/p>\n\n<\/p>\n<\/div>\nAnd here is the code for the example<\/p>\n
var StateMain = {\r\n preload: function() {\r\n game.load.image(\"ship\", \"images\/ship.png\");\r\n },\r\n create: function() {\r\n this.ship = game.add.sprite(game.world.centerX, game.world.centerY, \"ship\");\r\n this.ship.anchor.set(0.5, 0.5);\r\n game.input.onUp.add(this.clickCanvas, this);\r\n },\r\n clickCanvas: function() {\r\n \/\/make an object from the mouse postion\r\n var obj1 = {\r\n x: game.input.x,\r\n y: game.input.y\r\n };\r\n \/\/get the angle between the mouse and the ship and assign that to the\r\n \/\/ship's angle\r\n this.ship.angle = this.getAngle(obj1, this.ship);\r\n },\r\n getAngle: function(obj1, obj2) {\r\n \/\/I use the offset because the ship is pointing down\r\n \/\/at the 6 o'clock position\r\n \/\/set to 0 if your sprite is facing 3 o'clock\r\n \/\/set to 180 if your sprite is facing 9 o'clock\r\n \/\/set to 270 if your sprite is facing 12 o'clock\r\n \/\/\r\n offSet = 90;\r\n \/\/ angle in radians\r\n var angleRadians = Math.atan2(obj2.y - obj1.y, obj2.x - obj1.x);\r\n \/\/ angle in degrees\r\n var angleDeg = (Math.atan2(obj2.y - obj1.y, obj2.x - obj1.x) * 180 \/ Math.PI);\r\n \/\/add the offset\r\n angleDeg += offSet;\r\n return angleDeg;\r\n },\r\n update: function() {}\r\n}<\/pre>\n