How to set contactDelegate for physicsWorld in SpriteKit?

我的梦境 提交于 2020-02-06 23:32:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!