1
\$\begingroup\$

the result of the angle between my touch and the middle,bottom of the screen gives me 180 when the touch is on the right side of the screen, and 0 when it is on the left. I don't understand why...

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    let refPoint = CGPointMake(self.frame.size.width/2, self.frame.size.height)
    let anyTouch: UITouch = touches.anyObject() as UITouch
    let touch = anyTouch.locationInView(self.view!)

    //180 is inversed? 180 is when touch is on the right side...
    let dy = (refPoint.y - touch.y) //opposite
    let dx = (refPoint.x - touch.x) //adjacent

    let rad = atan2(dy, dx)
    let angle = rad * 180 / CGFloat(M_PI)
    println("angle : \(angle) ")
}

Would someone know how to solve this?

Thanks

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

You're not taking into account the inverted Y axis in comparison to the normal X axis in most (maybe all?) programming languages. The top left corner of the screen is (0, 0), and is positive in the right and down directions.

So if the bottom middle of your screen is, for example, (300, 400), and you click at (0, 400), then your triangle will be a first quadrant triangle instead of the second quadrant triangle you expected.

let dy = (refPoint.y - touch.y) --> let dy = (400 - 400)

let dx = (refPoint.x - touch.x) --> let dx = (400 - 0)

This will give you a triangle with two points at (300, 400) and one point at (400, 400) in the normal X/Y coordinate plane. Therefore, to fix this, simply change your code to:

let dy = (refPoint.y - touch.y)
let dx = (touch.x - refPoint.x)

This should fix your inversed angles issue. Something you should note however is that since the Y axis is inverted, it causes the coordinate plane to be practically "flipped" across the X axis, and that angles in screen space will increase going clockwise and decrease going counterclockwise.

Hope this helps!

\$\endgroup\$
1
  • \$\begingroup\$ You might also want to add that, in screen space, angles increase clockwise unlike math class where they increase counterclockwise. \$\endgroup\$
    – John K
    Mar 4, 2015 at 1:30
2
\$\begingroup\$

You wil want to subtract the touch with the ref point:

//180 is inversed? 180 is when touch is on the right side...
let dy = (touch.y - refPoint.y) //opposite
let dx = (touch.x - refPoint.x) //adjacent

This results in the (dx, dy) vector being from the refPoint to the touch point (as you would expect).

\$\endgroup\$
2
  • \$\begingroup\$ thanks ratchetfreak, it was indeed right, except the dy should be (ref.y - touch.y) . otherwise it gives negative values. Thank you very much for the answer \$\endgroup\$
    – Paul
    Mar 4, 2015 at 16:05
  • 1
    \$\begingroup\$ negative values can be handled by adding 2pi to the result \$\endgroup\$ Mar 4, 2015 at 16:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .