I want to setup my SpriteKit Game in a more ordered and clearer way, so I decided to make use of classes for each type of sprite node.
In my case I created a separate Player class in swift which looks like this
import SpriteKit
class Player: SKSpriteNode {
func initializePlayer() {
self.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.size.width, height: self.size.height))
self.physicsBody?.affectedByGravity = true
}
func moveLeft () {
print("left")
}
func moveRight () {
print("right")
}
}
I reference this Sprite Node in the Scene Editor´s Custom Class inspector correctly and I can trigger the class methods without any problem - so this works well.
I reference the Player class in my GameScene like this:
class GameplayScene: SKScene {
var player: Player = Player()
let myNode = SKSpriteNode(imageNamed: "player")
override func didMove(to view: SKView) {
player.initializePlayer()
}
}
But the physics body is not applied, and I can not figure out why this is the case.
After I added the physics body to the sprite node, I would expect the node to fall down off the screen. But this does not happen and I can not figure why.
Does anyone have a clue how I can apply a physics body from within the class?