0
\$\begingroup\$

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?

\$\endgroup\$
1
  • \$\begingroup\$ If you get stuck on this, you won't get far. Here. \$\endgroup\$
    – Vaillancourt
    Commented Mar 2, 2016 at 17:29

1 Answer 1

4
\$\begingroup\$

Consider trigonometry's unit circle (image source):

The Unit Circle

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.

\$\endgroup\$
5
  • \$\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 zero cos(0)=1 and sin(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\$
    – user1430
    Commented Mar 2, 2016 at 20:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .