开发者

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

开发者 https://www.devze.com 2023-01-31 17:39 出处:网络
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 us

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 ap开发者_如何学Goart. Can anybody just explain what I should be doing?


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. 


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号