Search code examples
iosswiftsprite-kitskphysicsbody

How do I draw a filled circle using SpriteKit?


I am trying to draw a filled circle in SpriteKit.

I am currently drawing a circle as such.

node.physicsBody = SKPhysicsBody(circleOfRadius: radius)
node.fillColor = color
node.strokeColor = node.fillColor

I need this circle to be filled at a certain level based on a value between 0.0 and 1.0. How can I achieve this effect?

enter image description here

For example, the circle above is filled at a value of 0.5.


Solution

  • I only have time to give you a partial answer. As Carrl said, you can draw the kind of shape you're looking for using Core Graphics (except I used UIBezierPath which is built on top of it):

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), false, 0)
    UIColor.greenColor().set()
    let p = UIBezierPath()
    p.moveToPoint(CGPointMake(0, 50))
    p.addArcWithCenter(CGPointMake(50, 50), radius: 50, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: true)
    p.closePath()
    p.fill()
    p.removeAllPoints()
    p.moveToPoint(CGPointMake(0, 50))
    UIColor.greenColor().colorWithAlphaComponent(0.5).set()
    p.addArcWithCenter(CGPointMake(50, 50), radius: 50, startAngle: CGFloat(M_PI), endAngle: CGFloat(2 * M_PI), clockwise: true)
    p.closePath()
    p.fill()
    let im1 = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    

    circle

    You still need to figure out how to use this as a texture in an SKSpriteNode, but you should be able to find an answer on this site. (SKShapeNode might be an option, but last time I tried using it in a Swift Playground, I recall it threw an error while trying to fill the shape node's path.)