How to draw a circle in swift using spriteKit?

elpita picture elpita · Nov 4, 2014 · Viewed 23.1k times · Source

I just started doing ios development with swift and I can't figure out how to draw a circle. I'm just trying to draw a circle, set it to a variable and display in on the screen so I can later use it as the main player. Could anyone tell me how to do this or provide me with the code for this?

I found this code online:

var Circle = SKShapeNode(circleOfRadius: 40)
Circle.position = CGPointMake(500, 500)
Circle.name = "defaultCircle"
Circle.strokeColor = SKColor.blackColor()
Circle.glowWidth = 10.0
Circle.fillColor = SKColor.yellowColor()
Circle.physicsBody = SKPhysicsBody(circleOfRadius: 40)
Circle.physicsBody?.dynamic = true //.physicsBody?.dynamic = true
self.addChild(Circle)

but when I put this on xcode and run the application nothing comes up in the game scene.

Answer

Voltaire's Ghost picture Voltaire's Ghost · Mar 28, 2015

screenshot

If you just want to draw one simple circle at some point it's this:

func oneLittleCircle(){

    var Circle = SKShapeNode(circleOfRadius: 100 ) // Size of Circle
    Circle.position = CGPointMake(frame.midX, frame.midY)  //Middle of Screen
    Circle.strokeColor = SKColor.blackColor()
    Circle.glowWidth = 1.0
    Circle.fillColor = SKColor.orangeColor()
    self.addChild(Circle)
}

The below code draws a circle where the user touches. You can replace the default iOS SpriteKit Project "GameScene.swift" code with the below.

screenshot

//
// Draw Circle At Touch .swift
// Replace GameScene.swift in the Default SpriteKit Project, with this code.


import SpriteKit

class GameScene: SKScene {
override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    scene?.backgroundColor = SKColor.whiteColor()  //background color to white

}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        makeCirlceInPosition(location)  // Call makeCircleInPostion, send touch location.
    }
}


//  Where the Magic Happens!
func makeCirlceInPosition(location: CGPoint){

    var Circle = SKShapeNode(circleOfRadius: 70 ) // Size of Circle = Radius setting.
    Circle.position = location  //touch location passed from touchesBegan.
    Circle.name = "defaultCircle"
    Circle.strokeColor = SKColor.blackColor()
    Circle.glowWidth = 1.0
    Circle.fillColor = SKColor.clearColor()
    self.addChild(Circle)
}
  override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
}}