nicolime nicolime - 9 days ago 8
Swift Question

How to find touched Node within a UIRotationRecognizer (SpriteKit + Swift 3.0)

I have three nodes

lineBlock
of the same class
MovableBlock
on the screen. I want to rotate the
lineBlock
node someone is touching on the screen.

I've solved this for moving the correct
lineBlock
node in touchedMoved:


override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
touch = touches.first!
positionInScene = self.touch?.location(in: self)
let previousPosition = self.touch?.previousLocation(in: self)
let translation = CGVector(dx: (positionInScene?.x)! - (previousPosition?.x)!, dy: (positionInScene?.y)! - (previousPosition?.y)!)

if touchedNode?.name?.contains("LineBlock") == true {
(touchedNode as! MovableBlock).selected = true
(touchedNode as! MovableBlock).parent!.parent!.run(SKAction.move(by: translation, duration: 0.0))
}
}


But I have not been able to do the same within my UIRotationRecognizer function. In my rotate function, it simply rotates the first node, regardless of which lineBlock (of class MovableBlock) I am touching:

func rotate(_ sender: UIRotationGestureRecognizer){
if lineBlock.selected == true {
lineBlock.run(SKAction.rotate(byAngle: (-(self.rotationRecognizer?.rotation)!*2), duration: 0.0))
rotationRecognizer?.rotation = 0
}
}


For reference, here's how I define touchedNode (in touchBegan):

touches: Set<UITouch>, with event: UIEvent?) {
touch = touches.first!
positionInScene = self.touch?.location(in: self)
touchedNode = self.atPoint(positionInScene!)

Answer

UIGestureRecognizers have a location(in:UIView) method. You can use self.view?.convert(sender.location(in: self.view), to: self) to get the UIRotationGestureRecognizer's location and use logic similar to that in touchesBegan.

convert(_:to:) will make sure that the point is in your scene's coordinate space.

Comments