2015-11-14 121 views
0

我創建了兩個對象,一個牆壁和一個可以碰撞的玩家。如果他們碰撞,球員不應該能夠移入或移過牆壁。如果我設置massWall >> massPlayer,玩家有時可以在牆上移動。如果我沒有設置質量,那麼球員和牆會朝一個方向移動。我想要讓牆壁靜止不動,球員不能穿過牆壁。 我的代碼:Swift/SpriteKit碰撞檢測

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

有兩件事情需要改變。第一個是解決玩家穿牆的問題。這是通過使在playerNode這樣精確的碰撞檢測固定的(只是把這個了與physicsBody配置的其餘部分):

playerNode.physicsBody!.usesPreciseCollisionDetection = true 

接下來你需要讓你的牆壁沒有物理動態,這將阻止它當你的playerNode碰到它時反應。你不需要設置wallNodemass,你不需要它。所以應該添加類似這樣的東西(只需將其與physicsBody配置的其餘部分一起):

wallNode.physicsBody!.dynamic = false