collisionBitMask值在SpriteKit中不起作用

时间:2017-08-04 15:07:30

标签: swift sprite-kit skphysicsbody

我想让两个实体相互碰撞。我有一个结构来跟踪不同的物理类别:

struct PhysicsCategory {
    static let Player: Int32 = 0x1 << 1
    static let Obstacle: Int32 = 0x1 << 2
    static let Ground: Int32 = 0x1 << 3
}

我希望我的Player节点与我的Obstacle节点发生冲突。这是我的玩家节点的物理:

    self.physicsBody = SKPhysicsBody(rectangleOf: (self.size))
    self.physicsBody?.isDynamic = true
    self.physicsBody?.categoryBitMask = UInt32(PhysicsCategory.Player)
    self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Obstacle)
    self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Ground)

这是我的障碍节点的物理

    self.physicsBody = SKPhysicsBody(rectangleOf: self.size)
    self.physicsBody?.categoryBitMask = UInt32(PhysicsCategory.Obstacle)
    self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Player)
    self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Ground)
    self.physicsBody?.isDynamic = true
    self.physicsBody?.velocity = CGVector(dx: -240, dy: 0)
    self.physicsBody?.linearDamping = 0
    self.physicsBody?.friction = 0

当他们穿过小径时,他们只是穿过对方。但是,它们都与地面正常碰撞。我做错了什么?

1 个答案:

答案 0 :(得分:2)

第二次设置时,您正在覆盖collisionBitMask。您应该设置一个OR位掩码,其符号为|

替换

self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Obstacle)
self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Ground)

使用:

self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Obstacle) | UInt32(PhysicsCategory.Ground)

self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Player)
self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Ground)

使用:

self.physicsBody?.collisionBitMask = UInt32(PhysicsCategory.Player) | UInt32(PhysicsCategory.Ground)