I am trying to have objects fall from the top of the screen so I created a FallingBlock subclass that inherits from SKShapeNode. However, whenever I run my code, the blocks do not appear on the screen. I know these blocks are on screen because they come in contact with other objects, but they are unable to be seen. Below is my code:
import SpriteKit
class FallingBlock: SKShapeNode {
let color = [UIColor.red,UIColor.cyan,UIColor.green,UIColor.yellow,UIColor.orange,UIColor.systemPink].randomElement() as! UIColor
init(side: CGPoint) {
super.init()
self.path = CGPath(roundedRect: CGRect(x: side.x, y: side.y, width: 20, height: 20), cornerWidth: 3, cornerHeight: 3, transform: nil)
self.fillColor = color
self.strokeColor = color
self.position = side
self.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 20, height: 20))
self.physicsBody?.affectedByGravity = true
self.zPosition = 1
self.physicsBody?.categoryBitMask = PhysicsCategories.obstacleCategory
self.name = ObjectNames.obstacle
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
print("falling block reference deleted")
}
}
Within my GameScene I am running the following function:
func newObstacle() {
let side = [25,frame.width-25].randomElement() as! CGFloat
obstacle = FallingBlock(side: CGPoint(x: side, y: frame.maxY+15))
worldNode.addChild(obstacle)
deallocateObstacle()
}
I couldn't figure out a solution when the class inherits from an
SKShapeNode; however, I was able to figure out how to do it when it inherits from anSKNode. All that is required is to initialize theSKNodeand then add anSKShapeNode- with your desired attributes - as a child of theSKNodelike what is done below: