我希望SKSpriteNodes可以照顾自己的联系人检测。
就像Unity在GameObjects上有自己的OnTriggerEnter
方法一样。
但是我不知道如何在SpriteKit中实现这一目标,一些帮助会得到广泛应用
示例我将如何“运行”它:
示例球类:
import SpriteKit
class Ball: SKSpriteNode, SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
print("INSIDE BALL: ",contact.bodyA.node?.name, contact.bodyB.node?.name)
}
init(x: Int, y: Int) {
physicsWorld.contactDelegate = self ????
//setting up Physicsbody etc
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
示例场景文件
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
}
func didBegin(_ contact: SKPhysicsContact) {
print("INSIDE MAIN: ",contact.bodyA.node?.name, contact.bodyB.node?.name)
}
或者您如何管理大量的联系逻辑?
感谢您的帮助,如果提出的问题很奇怪,对此表示歉意
答案 0 :(得分:1)
我喜欢这样构造didBegin
代码:(可以联系的对象是blueBall,blueRectangle,greenBall,greenRectangle,redBall和redRectangle)
func didBegin(_ contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask {
case blueBallCategory | blueRectangleCategory:
print("Alive! Blue ball has hit blue rectangle.")
case greenBallCategory | greenRectangleCategory:
print("Alive! Green ball has hit green rectangle.")
case redBallCategory | redRectangleCategory:
print("Alive! Red ball has hit red rectangle.")
default :
print("Dead! Some other contact has occurred")
}
}
当然,如果您有更多的联系逻辑,则可以在每个case
语句中调用单独的函数。同样,您可以在发生碰撞的对象中调用碰撞方法:
case blueBallCategory | blueRectangleCategory:
contact.bodyA.hasHit(contact.bodyB)
或类似的