0

I'm working on a prototype for a game mechanic I want to implement in the future and have hit some odd behavior working with Python's trigonometric functions. I thought maybe Python's trig functions worked differently than Java, which is the language I'm used to, but I can't find any documentation or evidence to support that.

The problem is that I'm trying to encode small gestural movements as numbers representing the direction they've moved in:

Diagram 1

And then those numbers are a string representing the directions the user moved the mouse to create each segment of the drawing. I can then use the Levenshtein distance algorithm to determine the closest match to pre-defined "drawings".

The confusion is coming from the fact that I don't seem to be getting the correct theta values from the atan2 method. PyGame's coordinate system is standard top-left (0,0) origin with y increasing down. To calculate theta for the two points, I do:

theta = math.atan2((p2[1] - p1[1]), (p2[0] - p1[0]))
theta = ((theta + (math.pi * 2)) % (math.pi * 2))

After the user has finished drawing a gesture, it is represented as a series of points and the distance between them is defined. I iterate over these points and compare them to the point in front of them in the list to get the theta value of that line segment, and then encode it as a number 1-8:

DIRECTIONS = [...list of radian values of angles 0 through 2pi...]
for p in range(len(points) - 1):
    p1 = points[p]
    p2 = points[p + 1]
    theta = math.atan2((p2[1] - p1[1]), (p2[0] - p1[0]))
    theta = ((theta + (math.pi * 2)) % (math.pi * 2))
    closest = 0
    cDiff = (math.pi * 2)
    for i in range(len(DIRECTIONS)):
        direction = DIRECTIONS[i]
        diff = abs(theta - direction)
        if diff < cDiff:
            cDiff = diff
            closest = i
    if closest == (len(DIRECTIONS) - 1):
        dir.append(1) # redundancy so you can compare theta values > 315 to 0
    else:
        dir.append(closest + 1)

This should give me a string of numbers 1-8 representing the directions those line segments "moved". However, I've noticed weird results where certain angles seem to be "flipped", so for example:

Angle

Where a gesture in this direction should give me the number "2" to represent a 45 degree angle change, it instead gives me "8" (-45 degree angle change, or 7/4pi). I get similar results for all angles where the y-change is not 0. So basically any direction that isn't "1" or "5".

Does anyone know why this is happening?

Darin Beaudreau
  • 604
  • 4
  • 24
  • What is the direction of the y-axis? Note, by the way, that there's a typo: I instead of i. EDIT: you did write that the direction was downwards. – Stefan Jan 14 '19 at 21:48
  • I'm aware. StackExchange auto-corrects my lower-case i's. Also, y-axis increases downward, as is the norm for game engines. – Darin Beaudreau Jan 15 '19 at 12:31

0 Answers0