Advertisement

Problem with moving SDL rect at an angle?

Started by May 23, 2017 07:28 PM
1 comment, last by Khatharr 7 years, 6 months ago

I am trying to make a top down space shooter thing in SDL. I am trying to move the ships rect so that it goes forward at the angle the ship is at. From what I have read, in order to do this would do something like:


rect.y -= sin( angle*( PI/180 ) ) * speed;
rect.x -= cos( angle*( PI/180 ) ) * speed;

Is this what I should do? Because when I add this to my loop, the ship moves in the opposite direction, and the movement is usually curved, not straight. And if the angle is set to 0, the ship moves sideways. Any help is appreciated.

first thing: SDL_Rect uses integers for its values, and you are going to want to use floats.

next: if it moves in the "opposite" direction, just invert the sign on the math (ie change the - to a +)

next: moving sideways? where are you expecting an angle of 0 radians to be at? straight "up"? nope. in math cos(0) = 1 and sin(0) = 0. since you are using cos to modify your x value, then when the angle is 0 then you are changing your x component by the speed and the y component by 0

Advertisement

The sine and cosine operations are conceptually native to a mathematical coordinate system that look like this:
300px-Unit_circle_angles_color.svg.png

Note that:

  • Zero degrees points along the X axis in the positive direction.
  • Angles increase counter-clockwise.
  • Y increases upward
  • The origin is in the center

In 2D graphics you're often in a situation where the origin is at the top-left and Y increases downward, so you're going to get a reversed Y result relative to your coordinate system. It also means that your angles will rotate clockwise instead of counter-clockwise.
In the snippet you posted you are negating the X result from cosine. That's not what you want.

More importantly, you're very, very likely to be better off using X, Y vectors instead of angles. In that case you can just give your ship a heading, such as (0.6f, 0.8f). To move forward you multiply that vector by the thrust amount (units per second) and the timeslice (seconds elapsed since last calculation), then add the result to your position vector.

If you need the angle of the ship (to rotate the sprite, for instance) you can use atan(y / x) or atan2(y, x) to get the angle in radians. Remember that the x and y you provide need to be converted to the trig coordinate system shown above, and the result will be in that same system, so you may need to invert the y you pass and negate the resulting angle, depending on what SDL wants from you.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

This topic is closed to new replies.

Advertisement