没有动态的 Sprite Kit 碰撞

Sprite Kit Collision without dynamic

我想通过点击屏幕上的每一半来移动我的玩家节点。

一旦停止点击,节点也应该停止。正如我现在所拥有的那样,一旦触摸屏幕,玩家节点就是 dynamic = true,如果触摸结束它被设置为 dynamic = false,以避免玩家继续移动。使用此方法,Collision Detection不起作用。

是否有其他方法可以得到结果?

代码:

func addPlayer(){

    let Player1 = SKTexture(imageNamed: "Player1.png")
    Player1.filteringMode = .Nearest
    let Player2 = SKTexture(imageNamed: "Player2.png")
    Player2.filteringMode = .Nearest

    let Run = SKAction.animateWithTextures([Player1, Player2], timePerFrame: 0.5)
    let RunAnimation = SKAction.repeatActionForever(Run)

    Player = SKSpriteNode(texture: Player1)
    Player.size = CGSize(width: self.frame.size.width / 6.5, height: self.frame.size.height / 12)
    Player.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 1.2)
    Player.zPosition = 4
    Player.runAction(RunAnimation)

    Player.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 40, height: 60))
    Player.physicsBody?.allowsRotation = false
    Player.physicsBody?.usesPreciseCollisionDetection = true
    Player.physicsBody?.restitution = 0
    Player.physicsBody?.dynamic = true
    Player.physicsBody?.velocity = CGVectorMake(0, 0)

    Player.physicsBody?.categoryBitMask = PlayerCategory
    Player.physicsBody?.collisionBitMask = WallCategory
    Player.physicsBody?.contactTestBitMask = WallCategory

    self.addChild(Player)
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    let touch:UITouch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)

    if touchLocation.x < self.frame.size.width / 2 {

        Player.physicsBody?.dynamic = true
        Player.physicsBody?.applyImpulse(CGVectorMake(-35, 0))

    } else {

        Player.physicsBody?.dynamic = true
        Player.physicsBody?.applyImpulse(CGVectorMake(35, 0))
    }
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

    let touch:UITouch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)

    if touchLocation.x < self.frame.size.width / 2 {

        Player.physicsBody?.dynamic = false

    } else {

        Player.physicsBody?.dynamic = false
    }
}

如果您希望 body 停止因物理原因发生的任何运动,只需将 body 的速度设置为 0:

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

    let touch:UITouch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)

    if touchLocation.x < self.frame.size.width / 2 {      
        Player.physicsBody?.velocity = CGVectorMake(0, 0)
    } else {  
        Player.physicsBody?.velocity = CGVectorMake(0, 0)
    }
}