# Sin and Cos

• 05-30-2003
Disturbed1
Sin and Cos
I dont really know any trig or anything so im hoping someone will help me out.

I have a sprite on the screen that rotates.

Here is what om doing:
Code:

```Player1.x += cos(Player1.angle) * 4; Player1.y -= cos(Player1.angle) * 4;```
Will that work or am I doing something wrong? I use allegro so a full circle is 256 degrees... should I switch to radians or is there something wrong with that code snipet? My problem is I get some wierd movements from the sprite.
• 05-30-2003
Dissata
ummm...

Sine and Cosine are trig functions that relate to right triangles and their angle and length ratios.

this can be corelated to circles and rotating them, but just for your referance if the hypotonuse(sp?) of a right triangle is 1, and the one of the remaining angles is x then the adjacent line from the angle x is the cosine of x and the opposite of that angle is sine of x. i think cosine in a fixed point is like .8 or something similer.

this means that if you add cosine(angle)*4, you will recieve a constantly positive # (since there cannot be negative angles in a triangle, nor negative lengths). unless you have some sort of reset function all this will do is continualy move your sprite in a infinately down and right.
• 05-30-2003
Disturbed1
heh.. thanks.

I think im gonna hold off on this stuff until I actually take trig in school...
• 05-30-2003
MrWizard
Usually we use matrices to transform points. Here is the 2D rotation matrix.

[ cos(theta) -sin(theta) ][ x ]
[ sin(theta) cos(theta) ][ y ]

where x y is your pos. This comes out to

newX = x*cos(theta) - y*sin(theta)
newY = x*sin(theta) + y*cos(theta)

I'll derive it mathetmatically when I get home.
• 06-03-2003
J. Ewing
As Mr. Wizard mentioned, the best way to do rotations is with matricies. It's far more efficient.

However, the chunk of code you presented should work fine if you make one little change. They should not both be using the same trigonometric function. It should instead look something like this:

Player1.x += sin(Player1.angle) * 4;
Player1.y += cos(Player1.angle) * 4;

In truth, you should remove the "4" and replace it with some variable name such as "speed" as that's what it would represent in this case.

Incidentally, cosine will ~not~ give you a constantly positive value. Like the sine function, it will always return a value between positive and negative one.