为什么这些碰撞不会感觉到什么? (Swift SpriteKit)

时间:2017-06-09 04:39:29

标签: ios swift xcode sprite-kit physics

在我的项目中,我试图检测两个SKSpriteNodes之间的碰撞,但它不起作用。 这是我的物理类别代码 :

powershell -command "gci *.jpg | ren -newname { ($_.basename -replace '\s+\(.*\)') + '.jpg'};gci *.png | ren -newname { ($_.basename -replace '\s+\(.*\)') + '.png'}"

对于中立,敌人和球员身体

struct PhysicsCategory {
static let enemy : UInt32 = 0x1 << 1
static let player : UInt32 = 0x1 << 3
static let neutral : UInt32 = 0x1 << 2
 }

我的ContactHasBegan函数的代码:

  neutral = SKSpriteNode(imageNamed: "Cave-Bottom")
    neutral.size = CGSize(width: self.frame.width, height: self.frame.height / 8)
    neutral.position = CGPoint(x: 0, y: self.frame.height / -2.5)
    neutral.zPosition = 2
    neutral.physicsBody?.categoryBitMask = PhysicsCategory.neutral
    neutral.physicsBody?.collisionBitMask = PhysicsCategory.player
    neutral.physicsBody?.contactTestBitMask = PhysicsCategory.player
    neutral.physicsBody = SKPhysicsBody.init(rectangleOf:              neutral.size)

    enemy = SKSpriteNode(imageNamed: "spike")
    enemy.size = CGSize(width: 40, height: 40)
    enemy.position = CGPoint(x: 0, y: 0)
    enemy.zPosition = 2
    enemy.physicsBody = SKPhysicsBody.init(rectangleOf: enemy.size)
    enemy.physicsBody?.categoryBitMask = PhysicsCatagory.enemy
    enemy.physicsBody?.collisionBitMask = PhysicsCatagory.player
    enemy.physicsBody?.contactTestBitMask = PhysicsCatagory.player

    player = SKSpriteNode(imageNamed: "bob")
    player.size = CGSize(width: 40, height: 40)
    bob.zPosition = 3
    player.physicsBody?.categoryBitMask = PhysicsCatagory.player
    player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
    player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
    player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)

出于某种原因,它只能检测到玩家与敌人之间的碰撞并打印出“碰撞!”#34;并且didBeginContact函数中没有if语句测试为正。

1 个答案:

答案 0 :(得分:4)

因为玩家physicsBody没有设置categorycontactTest位掩码。

您尝试设置玩家物理系统的属性后,您已经创建了玩家物理:

player.physicsBody?.categoryBitMask = PhysicsCatagory.player
player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)

在前3行代码中,因为player.physicsBody是可选的,所以忽略该行的其余部分,因为没有physicsBody。

因此创建物理主体时将所有属性设置为默认值,即它与所有内容发生碰撞并且不接触任何内容。

您需要移动该行:

player.physicsBody = SKPhysicsBody.init(....

在您设置物理主体属性的代码之前:

player.physicsBody = SKPhysicsBody.init(rectangleOf: player.size)
player.physicsBody?.categoryBitMask = PhysicsCatagory.player
player.physicsBody?.collisionBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral
player.physicsBody?.contactTestBitMask = PhysicsCatagory.enemy | PhysicsCatagory.neutral