问题
I have just encountered a problem when assigning contactDelegate to self (GameScene).
override func didMoveToView(view: SKView)
{
self.physicsWorld.contactDelegate = self
/* ... */
}
Unfortunately, I get an error:
Cannot assign a value of type 'GameScene' to value of type 'SKPhysicsContactDelegate?'
This wouldn't happen in previous versions of Xcode (probably something new in Swift 2.0), so even in SpriteKit documentation on Apple Developer they have the same code I do.
How do I get around this? I have already tried to force casting
self.physicsWorld.contactDelegate = (self as! SKPhysicsContactDelegate)
but I got a runtime error (casting couldn't be performed).
Anyone knows how to delegate contacts to my GameScene?
回答1:
I know in my project (swift 1 i assume) you have to define the game scene as a SKPhysicsContact Delegate like so.
class GameScene: SKScene, SKPhysicsContactDelegate {
}
And to set it as the delegate I just do.
self.physicsWorld.contactDelegate = self
no "as" operator required.
回答2:
You probably forgot to add SKPhysicsContactDelegate
at the top of your class.
来源:https://stackoverflow.com/questions/32209725/how-to-set-contactdelegate-for-physicsworld-in-spritekit