Reputation: 791
I have a class called Bird, that is a SKSpriteNode. I do have it initialized, but I can't figure out how to set physicsBody and other properties of it in that same class rather than in GameScene class.
Bird class:
import SpriteKit
class Bird: SKSpriteNode {
init() {
let texture = SKTexture(imageNamed: "birdy")
let size = texture.size()
super.init(texture: texture, color: UIColor.clearColor(), size: CGSizeMake(size.width/4, size.height/4))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
A function for setting the properties of Bird in GameScene:
var birdSprite: Bird!
func setupBird() {
birdSprite = Bird()
birdSprite.position = CGPointMake(size.width*0.5, size.height*0.2)
birdSprite.zPosition = Layer.Bird.rawValue
self.addChild(birdSprite)
birdSprite.physicsBody = SKPhysicsBody(circleOfRadius: birdSprite.size.width/2)
birdSprite.physicsBody?.categoryBitMask = PhysicsCategory.Bird
birdSprite.physicsBody?.collisionBitMask = PhysicsCategory.None
birdSprite.physicsBody?.contactTestBitMask = PhysicsCategory.Desk
birdSprite.physicsBody?.allowsRotation = false
birdSprite.physicsBody?.restitution = 0
birdSprite.physicsBody?.usesPreciseCollisionDetection = true
}
I tried setting its physics body by defining it in Bird class, with self.physicsBody = ..., but that gave me an error, as well as setting it the same way inside the init function, so I didn't include it here in the code.
The reason I want to do it in a separate class is that I would like to learn how to write well organized code, so that the code would be more readable and self explanatory. But I am more or less a beginner at Swift and programming in general, so the lack of experience and knowledge is giving me some troubles.
Any help or suggestion is welcome!
Upvotes: 0
Views: 368
Reputation: 533
Have you tried to set these properties after the call to super.init()
?
Since the properties you want to set are from the superclass, these can only be setted after this call, like in:
init() {
let texture = SKTexture(imageNamed: "birdy")
let size = texture.size()
super.init(texture: texture, color: UIColor.clearColor(), size: CGSizeMake(size.width/4, size.height/4))
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width/2)
}
I don't know exactly what did you do first in the init()
, but maybe this is the case.
Upvotes: 2