pomo_mondreganto
pomo_mondreganto

Reputation: 2074

Asynchronous moving of 2 nodes sprite kit

I have 2 nodes, that I want to grab with 2 fingers asynchronously on my iPad. That's code for moving:

var ninjaMoving = false
var monsterMoving = false

var loc = CGPoint(x: 0.0, y: 0.0)
var prevLoc = CGPoint(x: 0.0, y: 0.0)

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        if !self.nodesAtPoint(location).isEmpty && (self.nodeAtPoint(location).physicsBody?.categoryBitMask == 1 || self.nodeAtPoint(location).physicsBody?.categoryBitMask == 3) {
            if self.nodeAtPoint(location).physicsBody?.categoryBitMask == 1 {
                ninjaMoving = true
            }
            else if self.nodeAtPoint(location).physicsBody?.categoryBitMask == 3 {
                monsterMoving = true
            }
        }
    }
}

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in touches as! Set<UITouch> {
        loc = touch.locationInNode(self)
        prevLoc = touch.previousLocationInNode(self)
    }
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in touches as! Set<UITouch> {
        let location = touch.locationInNode(self)
        if self.nodeAtPoint(prevLoc).physicsBody?.categoryBitMask == 1 {
            ninjaMoving = false
        }
        if self.nodeAtPoint(prevLoc).physicsBody?.categoryBitMask == 3 {
            monsterMoving = false
        }
    }
}

override func update(currentTime: CFTimeInterval) {
    if ninjaMoving {
        var x = playerNinja.position.x + (loc.x - prevLoc.x)
        var y = playerNinja.position.y + (loc.y - prevLoc.y)
        x = max(x, playerNinja.size.width / 2)
        x = min(x, size.width / 2 - playerNinja.size.width)
        y = max(y, playerNinja.size.height / 2)
        y = min(y, size.height - playerNinja.size.height / 2)

        playerNinja.position = CGPointMake(x, y)
    }
    if monsterMoving {
        var x = playerMonster.position.x + (loc.x - prevLoc.x)
        var y = playerMonster.position.y + (loc.y - prevLoc.y)
        x = max(x, self.size.width / 2 + playerMonster.size.width)
        x = min(x, size.width - playerMonster.size.width / 2)
        y = max(y, playerMonster.size.height / 2)
        y = min(y, size.height - playerMonster.size.height / 2)

        playerMonster.position = CGPointMake(x, y)

    }
}

But I can't move one of sprites to the left, and another to the right at the same time. Is there any way to do that in sprite kit?

Upvotes: 0

Views: 208

Answers (1)

mrtksn
mrtksn

Reputation: 422

Please check the answer for this question: multitouch in spritekit

The idea is that you should track individual touches separately.

Upvotes: 1

Related Questions