I'm trying to detect whether the user is touching either the left or right hand side of the screen in an SKScene.
I've put the following code together however it is only outputting "Left" regardless of where is touched.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if(location.x < self.frame.size.width/2){
print("Left")
}
else if(location.x > self.frame.size.width/2){
print("Right")
}
}
}
If you are using the default scene for a SpriteKit project, the anchor point is (0.5, 0.5) which places the origin of the scene to the center. If you want to test the touch position is left or right, you should change the condition checking to (this will work regardless of anchor point):
for touch in touches {
let location = touch.location(in: self)
if(location.x < frame.midX){
print("Left")
}
else if(location.x > frame.midX){
print("Right")
}
}
More details at: SKScene