Use sin and cos


#1

Hi, I want to simulate circular motion using sin and cos with sdl. The problem is that it doesn’t work, it doesn’t make any movement. This is the code

void Game::Update()
{
while (!SDL_TICKS_PASSED(SDL_GetTicks(), ticksLastFrame + FRAME_TARGET_TIME))
{

	deltaTime = (SDL_GetTicks() - ticksLastFrame) / 1000;
	ticksLastFrame = SDL_GetTicks();
	projectilePosX = projectilePosX + cos(4.0f)*deltaTime;//projectileVelX;
	//projectilePosY = projectilePosY + sin(30.0f) *5* deltaTime;//projectileVelY;
}

}


#2

Put SDL_GetTicks() (or something that changes with time) as the argument to cos() and sin(). Make it the same frequency and phase if you want a continuous looping motion. Also, multiply it by something big, so you can see it on the screen: cos() will be -1 to 1 pixels, 200*cos() will be -200 to 200 pixels.


#3

A little bit of trigonometry is required here so I’d like to complement JonnyD’s answer. The basic formula for a circular motion is:

x = A cos(ωt)
y = A sin(ωt)

with ω being the angular velocity, i.e. 2π multiplied by the frequency (in Hertz or turns per second) and A the amplitude, e.g. in pixels. ω is a value that increases indefinitely so you need to keep a variable that increases with time. Both sine and cosine vary between -1 and 1 so you must multiply the result with a value big enough so that you can see the result on a display.