简体   繁体   English

使用多个 didBegin 联系人 - SpriteKit

[英]Using multiple didBegin contact - SpriteKit

I would like to have so SKSpriteNodes can take care of there own contact detection.我希望 SKSpriteNodes 可以处理自己的接触检测。 Much like Unity have there own OnTriggerEnter methods on there GameObjects.就像 Unity 在 GameObjects 上有自己的OnTriggerEnter方法一样。 But I do not know how to achieve that in SpriteKit, some help would much appriciated但我不知道如何在 SpriteKit 中实现这一点,一些帮助会很受欢迎

Example how I would "like" it to work:示例我如何“希望”它工作:

example Ball class:示例球 class:

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")
    }

}

example scene file示例场景文件

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)
    }

Or how do you manage large amount of contact logic?或者你如何管理大量的联系逻辑?

Thanks for any help and sorry if the questions is weirdly formulated感谢您的帮助,如果问题的表述很奇怪,我们深表歉意

I like to structure my didBegin code this way: (the objects that can contact are blueBall, blueRectangle, greenBall, greenRectangle, redBall and redRectangle)我喜欢这样构造我的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")
    }
}

You could, of course, call separate functions inside each case statement if you have much more contact logic.当然,如果您有更多的联系逻辑,您可以在每个case语句中调用单独的函数。 Equally you could call a collision method in the object that has collided:同样,您可以在发生碰撞的 object 中调用碰撞方法:

    case blueBallCategory | blueRectangleCategory:
       contact.bodyA.hasHit(contact.bodyB)

or similar.或类似的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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