How to draw a circle in swift using spriteKit?
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.
//
// 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 */
}}
In modern Swift(Xcode 13.2.1 and Swift 5.1), try using apple's default game template when creating a project. Then get rid of the actions file and replace the contents of the class GameScene
in gameScene.swift with this:
override func didMove(to view: SKView) {
let Circle = SKShapeNode(circleOfRadius: 40)
Circle.position = CGPoint(x: 100, y: 100)
Circle.name = "defaultCircle"
Circle.strokeColor = SKColor.black
Circle.glowWidth = 10.0
Circle.fillColor = SKColor.yellow
Circle.physicsBody = SKPhysicsBody(circleOfRadius: 40)
Circle.physicsBody?.isDynamic = false
self.addChild(Circle)
}
Swift
let circle = SKShapeNode(circleOfRadius: 100 ) // Create circle
circle.position = CGPoint(x: 0, y: 0) // Center (given scene anchor point is 0.5 for x&y)
circle.strokeColor = SKColor.black
circle.glowWidth = 1.0
circle.fillColor = SKColor.orange
addChild(circle)