Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating Oscillating Images With Swift Extensions

DZone's Guide to

Creating Oscillating Images With Swift Extensions

Using Swift's extension feature to create moving images that ignore gravity and other forces on the object.

· Mobile Zone
Free Resource

Recently I needed a image in my iOS app that was oscillating. I ran into an example of Swift code that showed how to do it and it was actually quite easy to do (for the theory behind the formula see this). The code makes use of the ‘extension’ feature in Swift. This is a really cool feature in Swift. The feature allows you to extend the functionality of a class without having to extend the class (like you would do in Java for instance). For a basic example of the feature see this example.
In my example the feature is used to extend the functionality of the SKAction class, another cool thing in the iOS SpriteKit library.

The extension looks like this:


let π = CGFloat(M_PI)

extension SKAction {
    static func oscillate(amplitude a: CGFloat, timePeriod t: CGFloat, midPoint: CGPoint) -> SKAction {
        let action = SKAction.customActionWithDuration(Double(t)) { node, currentTime in
            let displacement = a * sin(2 * π * currentTime / t)
            node.position.y = midPoint.y - displacement
        }
        return action
    }
}

You can use the extension and apply it to a SpriteNode in your GameScene.swift for example like this:



import SpriteKit

class GameScene: SKScene {

    let ball = SKSpriteNode(imageNamed: "ball")

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        backgroundColor = SKColor.clearColor()

        ball.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)

        addChild(ball)

        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width)
        ball.physicsBody?.restitution = 0.0
        ball.physicsBody?.linearDamping = 0.0
        ball.size = CGSize(width: 100, height: 100)
        ball.physicsBody?.affectedByGravity = false

        let oscillate = SKAction.oscillation(amplitude: size.height/4, timePeriod: 8, midPoint: ball.position)
        ball.runAction(SKAction.repeatActionForever(oscillate))
    }
}

As you can see I ignored the gravity and other ‘forces’ on the object.
This results in the following behaviour:
bouncing-ball

Topics:
ios ,swift ,mobile ,animation

Published at DZone with permission of Pascal Alma. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}