使用多个didBegin联系人-SpriteKit

问题描述 投票:0回答:1

我想让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)
    }

或者您如何管理大量的联系逻辑?

感谢您的帮助,如果提出的问题很奇怪,请对不起

ios swift xcode sprite-kit game-engine
1个回答
0
投票

我喜欢这样构造我的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)

或类似。

© www.soinside.com 2019 - 2024. All rights reserved.