I'm trying to make a class from this node so I can make various objects from it, but Xcode keeps saying "Expected Declaration". How can I make a class from my node? Here is the code that's giving me an error: P.S. I am relatively new to StackOverflow, so if my question needs more details please let me know instead of putting it on hold. Thanks!
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMove(to view: SKView) {
class nodeClass{
let platform = SKSpriteNode(color: UIColor.yellow, size: CGSize(width: 400, height: 60))
platform.xScale = 0.8
platform.yScale = 0.8
platform.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: platform.size.width, height: platform.size.width / 6))
platform.position = CGPoint(x: 150, y: -100)
platform.physicsBody?.categoryBitMask = 1
platform.physicsBody?.collisionBitMask = 0
platform.physicsBody?.isDynamic = false
platform.physicsBody?.affectedByGravity = false
self.addChild(platform)
}
}
}
Ad @Confused just said, you should avoid declaring a class inside a method.
Here's a possible solution
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMove(to view: SKView) {
let platform = Platform(size: CGSize(width: 400, height: 60))
platform.xScale = 0.8
platform.yScale = 0.8
platform.position = CGPoint(x: 150, y: -100)
self.addChild(platform)
}
}
class Platform: SKSpriteNode {
init(size: CGSize) {
super.init(texture: nil, color: .yellow, size: size)
let physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: size.width, height: size.width / 6)) // Are you sure about this??
physicsBody.categoryBitMask = 1
physicsBody.collisionBitMask = 0
physicsBody.isDynamic = false
physicsBody.affectedByGravity = false
self.physicsBody = physicsBody
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}