How to draw a circle in swift using spriteKit? - ios

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.

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 */
}}

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)

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)
}

try this
var circle : CGRect = CGRectMake(100.0, 100.0, 80.0, 80.0) //set your dimension
var shapeNode : SKShapeNode = SKShapeNode()
shapeNode.path = UIBezierPath.bezierPathWithOvalInRect(circle.CGPath)
shapeNode.fillColor = SKColor.redColor()
shapeNode.lineWidth = 1 //set your border
self.addChild(shapeNode)

I check your code it works but what maybe happening is the ball disappears because you have dynamic as true. turn it off and try again. the ball is dropping out of the scene.
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 = false //set to false so it doesn't fall off scene.
self.addChild(Circle)

Related

SKSpriteNode shadow rendering incorrectly?

I'm using Xcode 11.4.1 and Swift 5.2.2, and I am trying cast a shadow using an SKLightNode onto a circular SKSpriteNode.
However, the shadow is cast over the rectangular frame of the SpriteNode rather than the circle image png that I am using.
This is the desired effect
This is what happens
In the first image, I am using a 611x611px circle png while in the second I am using a 612x612 png. I have found that this "corner shadow" happens only when using specific image dimensions to create the SpriteNode.
Specifically, through my testing, square images with size <688px and >601px display no corner shadow, except sizes exactly 612 and 608. I am testing this in a playground but the same problem occurs in a full xcodeproj.
What have I done wrong here? I doubt my code is the issue but here it is:
import PlaygroundSupport
import SpriteKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
let background = SKSpriteNode(color: UIColor.blue, size: frame.size)
background.zPosition = 0
background.position = CGPoint(x: frame.midX, y: frame.midY)
background.lightingBitMask = 1
addChild(background)
let light = SKLightNode()
light.zPosition = 100
light.categoryBitMask = 1
light.falloff = 0.5
light.lightColor = UIColor.white
light.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(light)
let sprite = SKSpriteNode(imageNamed: "612.png")
sprite.color = UIColor.yellow
sprite.colorBlendFactor = 1
sprite.zPosition = 3
sprite.position = CGPoint(x: frame.midX, y: frame.midY + 100)
sprite.size = CGSize(width: 100, height: 100)
sprite.physicsBody = SKPhysicsBody(circleOfRadius: 50)
sprite.physicsBody?.categoryBitMask = 2
sprite.shadowCastBitMask = 1
sprite.lightingBitMask = 1
sprite.physicsBody?.isDynamic = false
addChild(sprite)
}
}
let sceneView = SKView(frame: CGRect(x:0 , y:0, width: 640, height: 480))
let scene = GameScene()
scene.scaleMode = .aspectFill
scene.size = sceneView.frame.size
sceneView.presentScene(scene)
PlaygroundSupport.PlaygroundPage.current.liveView = sceneView

SpriteKit: A gap between SKSpriteNodes

When the blue square falls down on the red one a gap will remain. But when I make the blue square fall from a lower position there is no gap. Also when I give the blue square a higher mass the gap (on the ground) under the red square disappears and when the mass is too high the red square is gone.
I also made the squares smaller because the amount of pixels didn't equal the pixels of the png file which led to an even bigger gap. And when I set "showsPhysics" to true there is also a gap to see and even bigger when the squares are not scaled down.
Gap between SKSpriteNodes (picture)
//: Playground - noun: a place where people can play
import UIKit
import SpriteKit
import PlaygroundSupport
class Scene: SKScene {
var square = SKSpriteNode(texture: SKTexture(imageNamed: "red"), size: SKTexture(imageNamed: "red").size())
var square2 = SKSpriteNode(texture: SKTexture(imageNamed: "blue"), size: SKTexture(imageNamed: "blue").size())
var label = SKLabelNode(fontNamed: "Chalkduster")
override func didMove(to view: SKView) {
self.addChild(square)
self.addChild(square2)
self.addChild(label)
}
override func didChangeSize(_ oldSize: CGSize) {
// Add Scene Physics
self.physicsBody?.usesPreciseCollisionDetection = true
self.physicsBody = SKPhysicsBody(edgeLoopFrom: CGRect(x: -1, y: -1, width: self.size.width + 2, height: self.size.height + 2))
self.backgroundColor = UIColor.white
self.physicsBody?.usesPreciseCollisionDetection = true
//Add square
square.texture?.usesMipmaps = true
square.zPosition = 11
square.physicsBody = SKPhysicsBody(rectangleOf: square.size)
square.physicsBody?.usesPreciseCollisionDetection = true
square.physicsBody?.mass = 0.1
square.physicsBody?.allowsRotation = false
square.physicsBody?.usesPreciseCollisionDetection = true
square.setScale(0.25)
square.position = CGPoint(x: self.frame.width / 2, y: self.square.size.height)
square.name = "square"
//Add square2
square2.texture?.usesMipmaps = true
square2.zPosition = 11
square2.physicsBody = SKPhysicsBody(rectangleOf: square2.size)
square2.physicsBody?.usesPreciseCollisionDetection = true
square2.physicsBody?.mass = 0.1
square2.physicsBody?.allowsRotation = false
square2.physicsBody?.usesPreciseCollisionDetection = true
square2.setScale(0.25)
square2.position = CGPoint(x: self.frame.width / 2, y: self.square.size.height * 6)
square2.name = "square2"
//Add label
label.fontSize = 30
label.text = "w: \(self.frame.size.width) h: \(self.frame.size.height)"
label.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height - 30)
label.fontColor = UIColor.black
label.zPosition = 100
}
}
class ViewController: UIViewController {
let scene = Scene()
var viewSize = CGSize(width: 0, height: 0)
override func loadView() {
self.view = SKView()
}
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
view.frame = CGRect(origin: CGPoint(x: -1, y: -1), size: viewSize)
view.presentScene(scene)
view.showsPhysics = false
view.showsFPS = true
view.showsNodeCount = true
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scene.size = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height)
}
}
PlaygroundPage.current.liveView = ViewController()
As proof from the print commands, there is no actual gap between the sprite nodes, and with second proof from a super-zoomed-in-screenshot:
The playground you provided does not replicate an issue, which makes me wonder... what is going on with your project?
pg #2:
The scene's width and height has to be multiplied by 2. So the scene has to be 4 times bigger than the ViewControllers view. It's also like that in the game template that Apple provides for Spritekit.
scene.size = CGSize(width: self.view.frame.size.width * 2, height: self.view.frame.size.height * 2)
https://github.com/simon2204/Playground

SKSpriteNode losing velocity upon collision

I am making an iOS app and running into some problems with physics. As you can tell by the .GIF below, when I rotate the hexagon and the ball hits the rectangle at an angle, it loses some of its velocity and doesn't bounce as high. This is because of the reason shared here (basically because I am constraining the balls horizontal position, it's only using the vertical velocity when hitting an angle, thus losing speed).
I cannot for the life of me figure out a solution to fix this problem. Does anybody have any ideas??
Code for Ball node:
func createBallNode(ballColor: String) -> SKSpriteNode {
let ball = SKSpriteNode(imageNamed: ballColor)
ball.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)+30)
ball.zPosition = 1
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
ball.physicsBody?.affectedByGravity = true
ball.physicsBody?.restitution = 1
ball.physicsBody?.linearDamping = 0
ball.physicsBody?.friction = 0
ball.physicsBody?.categoryBitMask = ColliderType.Ball.rawValue
ball.physicsBody?.contactTestBitMask = ColliderType.Rect.rawValue
ball.physicsBody?.collisionBitMask = ColliderType.Rect.rawValue
let centerX = ball.position.x
let range = SKRange(lowerLimit: centerX, upperLimit: centerX)
let constraint = SKConstraint.positionX(range)
ball.constraints = [constraint]
return ball
}
Yes, the problem is probably causes by the ball hitting the hexagon when it is not perfectly "aligned". In this case the ball loses vertical speed in favour of the horizontal axis.
Since you want a "discrete logic" I believe in this scenario your should avoid physics (at least for the bouncing part). It would be much easier repeating an SKAction that moves the ball vertically.
Example
I prepared a simple example
class GameScene: SKScene {
override func didMove(to view: SKView) {
super.didMove(to: view)
let ball = createBallNode()
self.addChild(ball)
}
func createBallNode() -> SKSpriteNode {
let ball = SKSpriteNode(imageNamed: "ball")
ball.position = CGPoint(x: frame.midX, y: frame.minY + ball.frame.height / 2)
let goUp = SKAction.move(by: CGVector(dx: 0, dy: 600), duration: 1)
goUp.timingMode = .easeOut
let goDown = SKAction.move(by: CGVector(dx: 0, dy: -600), duration: 1)
goDown.timingMode = .easeIn
let goUpAndDown = SKAction.sequence([goUp, goDown])
let forever = SKAction.repeatForever(goUpAndDown)
ball.run(forever)
return ball
}
}
Update
If you need to perform a check every time the ball touches the base of the Hexagon you can use this code
class GameScene: SKScene {
override func didMove(to view: SKView) {
super.didMove(to: view)
let ball = createBallNode()
self.addChild(ball)
}
func createBallNode() -> SKSpriteNode {
let ball = SKSpriteNode(imageNamed: "ball")
ball.position = CGPoint(x: frame.midX, y: frame.minY + ball.frame.height / 2)
let goUp = SKAction.move(by: CGVector(dx: 0, dy: 600), duration: 1)
goUp.timingMode = .easeOut
let goDown = SKAction.move(by: CGVector(dx: 0, dy: -600), duration: 1)
goDown.timingMode = .easeIn
let check = SKAction.customAction(withDuration: 0) { (node, elapsedTime) in
self.ballTouchesBase()
}
let goUpAndDown = SKAction.sequence([goUp, goDown, check])
let forever = SKAction.repeatForever(goUpAndDown)
ball.run(forever)
return ball
}
private func ballTouchesBase() {
print("The ball touched the base")
}
}
As you can see now the method ballTouchesBase is called every time the ball is a te lower y coordinate. This is the right place to add a check for the color of your hexagon.

Ball dropping animation not working (Swift)

This code is supposed to drop a ball from the top of the screen to the bottom. And once it touches the bottom of the screen, it should appear back to the top of the screen. It doesn't relocate to the top and it stops moving. I want it to be a continuous loop that resets the ball.y position every time it touches the bottom.
import SpriteKit
class GameScene: SKScene {
let ball = SKShapeNode(circleOfRadius: 20)
let label = SKLabelNode(fontNamed: "Futura")
let movingObjects = SKSpriteNode()
override func didMoveToView(view: SKView) {
let sceneBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody = sceneBody
//Ball Transition
let ballTransition = SKAction.sequence([SKAction.fadeInWithDuration(1)])
ball.runAction(ballTransition)
//Ball function
ball.fillColor = SKColor.redColor()
ball.physicsBody = SKPhysicsBody(circleOfRadius: 25)
ball.physicsBody?.affectedByGravity = false
//Ball Movement
ball.position = CGPoint(x: self.frame.size.width/2, y: CGFloat(self.frame.size.height*1))
ballMovement()
movingObjects.addChild(ball)
self.addChild(label)
}
func ballMovement() {
let moveBall = SKAction.moveToY(self.frame.size.height*0, duration: 3)
let removeBall = SKAction.removeFromParent()
let moveAndRemove = SKAction.sequence([moveBall, removeBall])
ball.runAction(moveAndRemove)
//Label Sprite
label.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
label.fontColor = SKColor.redColor()
label.fontSize = 30
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
label.text = "\(ball.position.y)"
if ball.position.y < 26 {
ball.position = CGPoint(x: self.frame.size.width/2, y: CGFloat(self.frame.size.height*1))
}
}
}
removing the ball from its parent within the action and still acting on it elsewhere is going to become very fragile as your program gets more complex. Why not just do it all with the actions and let sprite kit worry about it ?
let moveBall = SKAction.moveToY(0, duration: 3)
let goBackUp = SKAction.moveToY(self.frame.size.height, duration:0)
let keepFalling = SKAction.sequence([moveBall, goBackUp])
ball.runAction(SKAction.repeatActionForever(keepFalling))

Why is my camera not centered?

I've noticed that the camera property my SKScene is nil. I remedied that by creating a SKCameraNode setting that equal to the camera property, setting its position and adding it to the scene. However, when I do this all of a sudden my objects are no longer in the center of the scene. They are all shifted in some way that does not make sense to me. What am I doing wrong?
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/*
// This is the problem code
let cam = SKCameraNode()
cam.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
self.camera = cam
self.addChild(cam)
*/
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
self.addChild(sprite)
}
}
Object appears in middle of scene, as expected.
Now the object is shifted to the left. Why?
UPDATE
The following code is giving me the behavior I want. The key is to reposition the camera every time the size of the SKScene changes. Thanks for the suggestions, they got me on the right track.
class GameScene: SKScene {
override func didChangeSize(oldSize: CGSize) {
if let view = self.view{
camera?.position = convertPointFromView(view.center)
}
}
override func didMoveToView(view: SKView) {
let cam = SKCameraNode()
cam.position = CGPoint(x: frame.midX, y:frame.midY)
self.camera = cam
self.addChild(cam)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.position = CGPoint(x: frame.midX, y: frame.midY)
self.addChild(sprite)
}
}

Resources