Created
January 3, 2016 14:26
-
-
Save gblancogarcia/4b8c22dd9f0272edde86 to your computer and use it in GitHub Desktop.
SpriteKit: creating a resizable circle with a ripple effect animation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SpriteKit | |
class CircleNode: SKShapeNode { | |
var radius: CGFloat { | |
didSet { | |
self.path = CircleNode.path(self.radius) | |
} | |
} | |
init(radius: CGFloat, position: CGPoint) { | |
self.radius = radius | |
super.init() | |
self.path = CircleNode.path(self.radius) | |
self.position = position | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
class func path(radius: CGFloat) -> CGMutablePathRef { | |
let path: CGMutablePathRef = CGPathCreateMutable() | |
CGPathAddArc(path, nil, 0.0, 0.0, radius, 0.0, CGFloat(2.0 * M_PI), true) | |
return path | |
} | |
func ripple(scale: CGFloat, duration: NSTimeInterval) { | |
if let scene = self.scene { | |
let currentRadius = radius | |
let finalRadius = radius * scale | |
let circleNode = CircleNode(radius: radius, position: position) | |
circleNode.strokeColor = strokeColor | |
circleNode.fillColor = fillColor | |
circleNode.position = position | |
circleNode.zRotation = zRotation | |
circleNode.lineWidth = lineWidth | |
circleNode.userInteractionEnabled = false | |
if let index = scene.children.indexOf(self) { | |
scene.insertChild(circleNode, atIndex: index) | |
let scaleAction = SKAction.customActionWithDuration(duration, actionBlock: { node, elapsedTime in | |
let circleNode = node as! CircleNode | |
let fraction = elapsedTime / CGFloat(duration) | |
circleNode.radius = currentRadius + (fraction * finalRadius) | |
}) | |
let fadeAction = SKAction.fadeAlphaTo(0, duration: duration) | |
fadeAction.timingMode = SKActionTimingMode.EaseOut | |
let actionGroup = SKAction.group([scaleAction, fadeAction]) | |
circleNode.runAction(actionGroup, completion: { | |
circleNode.removeFromParent(); | |
}) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have updated your gist to Swift 4.2 and added a few features. Check it out: https://gist.github.com/styrken/13f0dfe663825caa26cb96bc3bcd8669