Brian Carter
Brian Carter

Reputation: 157

Help me re-understand how to use sine to oscillate a graphic in (Objective) C

I feel silly asking this but I seem to have forgotten how to use sine effectively.

I'm working on an iPad app so I'm in ObjectiveC, and I'm just trying to get a UIView to oscillate slowly. Just using position.y + sin(counter) makes it move so fast it vibrates and I can't seem to define the period to slow it down.

I've found some code samples (mostly for generating sound waves) and they all combine so many things into one line of code I can't easily pull it apart. Can anybody just explain what I should be doing?

Upvotes: 0

Views: 533

Answers (3)

GolezTrol
GolezTrol

Reputation: 116110

sin (and cos) take a parameter in Radians. The name counter suggests that you're not using Radians.

So, you need to determine how many oscillations per second you want. Then, you can measure the time between the last and the current animation 'frame'. A whole wave is 2PI radians, so

Y = sin(2PI * Time * OccilationsPerSecond) * Amplitude. 

Upvotes: 2

John Parker
John Parker

Reputation: 54445

Whilst not the answer you're after, you could simply reduce the period you're calling the timer with if it's too fast. (That said, you can also set the duration for the CABasicAnimation - probably a much better approach, as iOS handles the animation for you, can auto-reverse to the initial settings, can be set to loop 'n' times, etc.)

That said, hopefully someone else will provide what you're after.

Upvotes: 0

duffymo
duffymo

Reputation: 308848

You need a formula like this:

x(t) = (x_max) sin(2*pi*frequency*t)

where

pi = 3.14159....
frequency = 1/period
t = time
x_max = maximum amplitude in the x-direction

If you want oscillation in the y-direction you need another function.

Upvotes: 1

Related Questions