我有三个精灵,它们可以相互碰撞,并且设置了contactTestBitMaskcategoryBitMask集。
我有两个精灵使用didBeginContact方法来查看它们是否发生了碰撞,并且效果很好,但是现在我不确定如何设置它来检查多个对象的接触,并根据碰撞的两个实体运行不同的函数。
我的PhysicsCategory

struct PhysicsCategory {
    static let None: UInt32 = 0
    static let All: UInt32 = UInt32.max
    static let Bird: UInt32 = 0b1
    static let Cloud: UInt32 = 0b10
    static let Desk: UInt32 = 0b100
    static let Star: UInt32 = 0b101
    static let StarSpecial: UInt32 = 0b110
}

didBeginContact中的GameScene方法:
func didBeginContact(contact: SKPhysicsContact) {
    var BirdBody: SKPhysicsBody?
    var DeskBody: SKPhysicsBody?
    var SpecialStarBody: SKPhysicsBody?
    //var SpecialStarBody: SKPhysicsBody
    if contact.bodyA.categoryBitMask == PhysicsCategory.Bird {
        BirdBody = contact.bodyA
        DeskBody = contact.bodyB
    } else if contact.bodyA.categoryBitMask == PhysicsCategory.Desk {
        BirdBody = contact.bodyB
        DeskBody = contact.bodyA
    } else if contact.bodyA.categoryBitMask == PhysicsCategory.StarSpecial {
        SpecialStarBody = contact.bodyA
    }
    if (DeskBody != nil) {
        birdSprite.BirdDidCollideWithDesk(BirdBody?.node as! Bird, desk: DeskBody?.node as! Desk, scoreClass: scoreClass, scoreLabel: scoreLabel)
    }
}

我要做的是检查bird是否与桌面接触,在这种情况下,它应该为bird和桌面运行函数,否则我想查看bird是否与SpecialStar接触,在这种情况下,我还没有编写什么要做的函数,但稍后,我将为这种情况调用不同的函数。我还添加了一些额外的sprites,因此如果有人能解释如何做到这一点,代码编写良好,不会导致任何错误,我将不胜感激。

最佳答案

你可以检查鸟是否和桌子有接触

if ((contact.bodyA.categoryBitMask == PhysicsCategory.Bird && contact.bodyB.categoryBitMask == PhysicsCategory.Desk) ||
(contact.bodyA.categoryBitMask == PhysicsCategory.Desk && contact.bodyB.categoryBitMask == PhysicsCategory.Bird)) {

    print("Bird, desk")
    // Handle contact bird with desk
}

鸟类与星空的接触
if ((contact.bodyA.categoryBitMask == PhysicsCategory.Bird && contact.bodyB.categoryBitMask == PhysicsCategory.StarSpecial) ||
(contact.bodyA.categoryBitMask == PhysicsCategory.Desk && contact.bodyB.categoryBitMask == PhysicsCategory.StarSpecial)) {

    print("Bird, StarSpecial")
    // Handle contact bird with StarSpecial
}

请注意:变量应该以小写字母开头。
为了保持代码清晰,我建议为每个节点创建类文件。
import Foundation
import SpriteKit

class Monster: SKSpriteNode {

    init(world: SKNode) {

    super.init(texture: SKTexture(imageNamed: "MonsterImageName"), color: UIColor.clearColor(), size: CGSizeMake(world.frame.size.width / 18, world.frame.size.width / 36))
    position = CGPointMake(world.frame.size.width / 2, world.frame.size.height / 2)
    zPosition = 100

    // etc
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

像这样添加
var monster = Monster.init(world)
world.addChild(monster)

关于swift - 在SpriteKit游戏中使用didBeginContact的正确方法-Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33439586/

10-09 02:44