I want a ship to move forward in the direction it's facing when you press the up key, but I don't know how to get a normalized vector from the angle the ship is facing. Can someone show me what code is necessary for moving something in a direction based on an angle?
1 Answer
Consider trigonometry's unit circle (image source):
Any (x
, y
) point on this circle is given by (cos(theta)
, sin(theta)
), where theta
is the angle from the x-axis. Assuming your facing angle is defined the same way (which it should be, because things will be easier for you), you can get a heading vector simply by using the (x
, y
) point on the unit circle as the x and y coordinates of your heading vector:
heading = [math.cos(angle), math.sin(angle)]
Since the unit circle has a radius of one, the length of the vector will also have a length of one, so it's already normalized for you.
-
\$\begingroup\$ This is exactly what I need, but it seems to be off for some reason. When the angle is 0, it moves the ship to the right instead of forward. Is it possible it's supposed to be secant or tangent or something or do I just need to add like 90 degrees to the angle? \$\endgroup\$ Commented Mar 2, 2016 at 20:36
-
\$\begingroup\$ @user3150635 Yes, this is what's supposed to happen. When
theta
is zerocos(0)=1
andsin(0)=0
giving us a vector (1,0) which points directly to the right. \$\endgroup\$ Commented Mar 2, 2016 at 20:41 -
\$\begingroup\$ so how do I get it to go down instead of right for example? \$\endgroup\$ Commented Mar 2, 2016 at 20:44
-
\$\begingroup\$ @user3150635 In the image file for your ship, rotate it so it's facing directly to the right. It may be as simple as that. \$\endgroup\$ Commented Mar 2, 2016 at 20:47
-
4\$\begingroup\$ @user3150635 This is what I meant by "assuming your facing angle is defined the same way..." -- you'll have a much easier time of it, in my experience, working under the assumption that an angle of 0 means "to the right" instead of "up," than you will going around and adjusting all your angles to add or subtract 90 degrees to them (but you can do that as well). \$\endgroup\$– user1430Commented Mar 2, 2016 at 20:49