Swift / SpriteKit碰撞检测

时间:2015-11-14 13:51:21

标签: swift sprite-kit collision-detection collision

我创造了两个物体,一个可以碰撞的墙和一个玩家。如果它们发生碰撞,则玩家不应该进入墙内或墙上。如果我设置了massWall>> massPlayer玩家有时可以在墙上移动。如果我没有设置质量,则玩家和墙壁会朝某个方向移动。我想要实现墙壁静止不动,玩家无法越过墙壁。 我的代码:

    func addWall(xPos: CGFloat, yPos: CGFloat){
    let wallNode = SKSpriteNode(imageNamed: "wall")

    wallNode.physicsBody = SKPhysicsBody(circleOfRadius: width/2)
    wallNode.physicsBody!.affectedByGravity = false
    wallNode.physicsBody!.categoryBitMask = ColliderType.Wall.rawValue
    wallNode.physicsBody!.contactTestBitMask = ColliderType.Player.rawValue
    wallNode.physicsBody!.collisionBitMask = ColliderType.Player.rawValue
    wallNode.physicsBody!.mass = 1000000

    let wall = Wall(node: wallNode)
    Walls.append(wall)
    wallNode.position.x = xPos
    wallNode.position.y = yPos
    wallNode.size = CGSize(width: width, height: width)
    addChild(wallNode)
}

func addPlayer(xPos: CGFloat, yPos: CGFloat){
    playerNode = SKSpriteNode(imageNamed: "player")

    playerNode.physicsBody = SKPhysicsBody(circleOfRadius: width/2)
    playerNode.physicsBody!.affectedByGravity = false
    playerNode.physicsBody!.categoryBitMask = ColliderType.Player.rawValue
    playerNode.physicsBody!.contactTestBitMask = ColliderType.Wall.rawValue
    playerNode.physicsBody!.collisionBitMask = ColliderType.Wall.rawValue
    playerNode.physicsBody!.mass = 1


    let player = Player(node: playerNode, healthPoints: 100, attack: 10)
    playerNode.position.x = xPos
    playerNode.position.y = yPos
    playerNode.size = CGSize(width: width, height: width)
    addChild(playerNode)
}

func didBeginContact(){}我没有任何代码,因为我现在不知道如何处理它。我无法撤消这一动作,因为我没有跟踪最后的动作。

1 个答案:

答案 0 :(得分:1)

您需要更改两件事。第一个是解决玩家穿越墙壁的问题。通过在playerNode上启用精确的碰撞检测来解决这个问题(只需将其与physicsBody配置的其余部分进行对比):

playerNode.physicsBody!.usesPreciseCollisionDetection = true

接下来你需要让你的墙没有动态物理,当你的playerNode撞到它时,这将阻止它做出反应。您无需设置mass的{​​{1}},也不需要它。所以应该添加这样的东西(只需将其与wallNode配置的其余部分放在一起):

physicsBody