How to create a rectangle in Sprite kit using Swift
18,456
Solution 1
You may want to use a SKShapeNode
, like this:
var barra = SKShapeNode(rectOfSize: CGSize(width: 300, height: 100))
barra.name = "bar"
barra.fillColor = SKColor.whiteColor()
barra.position = location
self.addChild(barra)
Here's Apple's documentation on SKShapeNode.
Solution 2
The way I was creating the rectangle was not the best, but the problem was the position I was inserting it on the game. This is how I've fixed it:
var barra = SKSpriteNode(color: SKColor.blackColor(), size: CGSizeMake(200, 200))
barra.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
barra.zPosition = 9 // zPosition to change in which layer the barra appears.
self.addChild(barra)
Related videos on Youtube
Author by
André Oliveira
I enjoy making scalable web apps using Serverless, Node.js and AWS.
Updated on September 14, 2022Comments
-
André Oliveira over 1 year
I'm trying to create a rectangle using swift on Sprite kit, since the rectangle needs to be used as an object in the scene, i assumed that i needed to create a SkSpriteNode, and them give it a size, but it did not worked, this is how i did it:
var barra = SKSpriteNode() barra.name = "bar" barra.size = CGSizeMake(300, 100) barra.color = SKColor.whiteColor() barra.position = CGPoint(x: 100, y: 100) self.addChild(barra)
Adding barra to the screen does not change the node counting.
Any help will be appreciated!
-
0x141E
let barra = SKSpriteNode(color:SKColor.whiteColor(),size:CGSize(300,100))
-
-
Simon over 8 yearsSKShapeNodes have very bad performance and they have memory issues. Just using the constructor with size, color is fine in this case.
-
Tiago Marinho over 8 years@Simon you're right. You can and should use SKSpriteNode instead of SKShapeNode when you are able to, due to performance, but by using SKShapeNode you are stating what you want to do more clearly (which is create a shape), and at first code clarity should be your biggest concern.