Movement Based off an Angle


(David Williams) #1

Today in my Advanced Math class, we learned about Radians for the first time ever. Well, after about 5 minutes, I figured out how to move something along a path using only an angle, so I thought I’d share it with the younger, less experienced programmers out there, like me.

Well, to begin with, let’s discuss Radians. A radian is just another way of measuring an angle. It can be written as a coordinate point where v is the angle, and w is the distance to a point. (w, v). So, (5, 50) is 5 units away, at an angle of 50 radians.

Consider the following picture:

Pi Radians is equal to 180 Degrees. Using all of this, I had a thought process kind of like this:

    angDeg = 90; //angle in degrees
angRad = angDeg * (Math.PI / 180); //angle in radians
dist = 5; //speed

sin(angRad) = yMovement/dist; //equation from the picture
cos(angRad) = xMovement/dist; //equation from the picutre

yMovement = dist * sin(angRad); //simplified
xMovement = dist * cos(angRad); //simplified

Now, say you want to fire a bullet from your gun. well, you can use FP.angle(player.x, player.y, Input.mouseX, Input.mouseY); to get the angle, but in Flashpunk it is the opposite for some reason, so this must be taken into account. So, say we have the angle in var x:int;. Now, to get the x and y modifier, we could go (inside of the bullet’s create or added function):

angRad = -x * (Math.PI / 180); //angle in radians (notice -x to fix the angle)
spd= 5; //speed to move at.

yMovement = spd * sin(angRad);
xMovement = spd * cos(angRad);

And then just apply those to the bullet’s x and y in the update function:

override public function update():void
{
    x += xMovement;
    y += yMovement;
}

And there you have it, what I learned today :stuck_out_tongue:


(Secretmapper) #2

(w,v) is a polar coordinate :wink:


(David Williams) #3

Thanks! I couldn’t quite remember what they were called, as I didn’t take notes. Just free styled it from memory.