ios - How do I move a SKSpriteNode up and down around its starting value in Swift? -
i'm working on game, there's skspritenode. want, node's location moves , down time. @ beginning, should have y value e.g. 500 . should move 200 px down (500+200=700) , should move 400 (700-400=300) creates , down, travels between 500+200 , 500-200 time. hope explained understandable. first, how effect , second, enter it? should use custom func? i'm programming swift (newbie swift)
i've written sample code can adapt purposes:
firstly, need π oscillation calculations:
// defined @ global scope. let π = cgfloat(m_pi)
secondly, extend skaction
can create actions oscillate node in question:
extension skaction { // amplitude - amount height vary by, set 200 in case. // timeperiod - time takes 1 complete cycle // midpoint - point around oscillation occurs. static func oscillation(amplitude a: cgfloat, timeperiod t: double, midpoint: cgpoint) -> skaction { let action = skaction.customactionwithduration(t) { node, currenttime in let displacement = * sin(2 * π * currenttime / cgfloat(t)) node.position.y = midpoint.y + displacement } return action } }
the displacement
above comes simple harmonic motion equation displacement. see here more information (their's rearranged little, it's same equation).
thirdly, putting together, in skscene
:
override func didmovetoview(view: skview) { let node = skspritenode(color: uicolor.greencolor(), size: cgsize(width: 50, height: 50)) node.position = cgpoint(x: size.width / 2, y: size.height / 2) self.addchild(node) let oscillate = skaction.oscillation(amplitude: 200, timeperiod: 1, midpoint: node.position) node.runaction(skaction.repeatactionforever(oscillate)) }
if needed oscillate node in x-axis i'd recommend adding angle
argument oscillate
method , using sin
, cos
determine how node should oscillate in each axis.
hope helps!
Comments
Post a Comment