Another really, really important thing to know for 2D game development is basic trig. For example, to turn an object (maybe a gun, for example) in the direction your mouse is pointing, get the X and Y values of the mouse cursor, and then use this (language neutral pseudocode):
Code: Select all
var angle = Math.atan2(mouseY - this.positionY, mouseX - this.positionX);
Or the non-object oriented way (for example, turning a gun):
Code: Select all
var angle = Math.atan2(mouseY - gun.Y, mouseX - gun.X);
That returns the rotation in radians, which is what most programming languages use (not degrees). And if you do need to rotate an object and only have degrees, you can turn them to radians this way:
Code: Select all
var rads = degrees * (Math.PI / 180);
And to move something at an angle (say animating a bullet being fired from a gun in the first example), you need a bit of trig for that, too. First, you need the angle in radians (shown here as a variable called "rads") you want the object to move along as well as the desired velocity you want the object to move (basically how fast you want it to move; this typically requires testing to find the right velocity), and then you can get the amount to add to the X and Y values for your object like this:
Code: Select all
var moveX = Math.sin(rads) * velocityX;
var moveY = Math.cos(rads) * velocityY;
//now you would actually animate the object
bullet.X = bullet.X + moveX;
bullet.Y = bullet.Y + moveY;
These 4 little procedures (including the
distance formula discussed above) here are among some of the most useful for a 2D game dev to know
