Doe Doe - 3 months ago 11x
Swift Question

Why in my SpriteKit game, movement logic is different?

I have a character. On tap on the screen I run this:

for touch in touches {
let location = touch.locationInNode(self)

print("Pos \(self.magician.position.x)")
if location.x >= self.magician.position.x {
self.movingRight = true
} else {
self.movingLeft = true

So, logic is: if the location.x is > than my character position.x, then it means, that I tapped on right side and my character must move in this direction, to the right. But I do not know why it moves to the left side when I tap on the right side.

Can someone explain me, why the logic is so different in SpriteKit?


Am I right in thinking that your character is a subclass of SKSpriteNode and this code is running in your character's code?


This will return the touch in the co-ordinate system of the given node (self). So if your character's anchor point is (0.5, 0.5) i.e. the middle of the node then location.x will be positive if you touched on the right side and negative if touched on the left side.

How this compares to your character's x & y position will depend upon your scene's anchor point, but your problem comes from trying to compare x values from 2 different coordinate systems.