简体   繁体   中英

How to set contactDelegate for physicsWorld in SpriteKit?

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?

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.

您可能忘了在SKPhysicsContactDelegate顶部添加SKPhysicsContactDelegate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM