Im using Pythonista 2 on my IPhone, and I'm trying to create a touch joystick. Its a simple concept, I touch somewhere on my screen, the joystick and the boundary snap to that position. Then, when I move my finger, the boundary stays still but the joystick inside moves, until i get to the edge of the boundary, then it follows on the circumference of the circle in between the center of the boundary and my finger. Here is the code:
def touch_moved(self, touch):
global r
r = 90
l = (touch.location-c[0],touch.location-c[1])
a = math.degrees(math.tan(l[1]/l[0]))
if (touch.location[0] - c[0])**2 + (touch.location[1] - c[1])**2 < r**2:
self.joystick.position = touch.location
else:
self.joystick.position = ((math.cos(a)*r)+c[0],(math.sin(a)*r)+c[1])`
But the joystick spazzes out on the circumference, so any help is appreciated.
You're using a
as a parameter to sin
and cos
, but it came from a call to math.degrees()
; trig functions always operate on radians, not degrees.
a
is derived from the result of a call to tan
, which should be a warning sign: tan
uses an angle as input, not normally as an output. You probably want the inverse function here, atan
. Actually, what you really want is math.atan2()
, which takes the horizontal and vertical values as separate parameters. As your code is written, you will get a divide-by-zero error if the touch position is directly above or below the center point.
Your calculation of l
seems wrong - shouldn't you be using indexes [0]
and [1]
with touch.location
, like you're doing two lines later?