0

I have a SPEEDLINK gamepad, and want to see the results of the movements in the gamepad. I wrote this:

import pygame
from pygame.locals import *
import random
pygame.init()

TV=pygame.display.set_mode((500,500))

joystick_count = pygame.joystick.get_count()
if joystick_count == 0:
    # No joysticks!
    print("Error, I didn't find any joysticks.")
else:
    # Use joystick #0 and initialize it
    my_joystick = pygame.joystick.Joystick(0)
    my_joystick.init()


x,y=400,400

pygame.draw.circle(TV,(100,200,40),(x,y),10)
pygame.display.flip()

my_joystick = pygame.joystick.Joystick(0)
clock=pygame.time.Clock()
my_joystick.init()

done=False

print pygame.joystick.get_count()

while not done:
     for e in pygame.event.get():
        if e.type==QUIT:
            done=True
        elif e.type==JOYBUTTONUP:
            x=my_joystick.get_axis(0)
            y=my_joystick.get_axis(1)
            print x,y

    clock.tick(60)

pygame.quit()

But when i move the hat, instead of 1 0 at hat-right it gives me 0.999969482422 0.0, and likewise at hat-down i get 0.0 0.999969482422 instead of 0 1. Why is it so and how can i get ONEs at those places just like other positions?

1 Answers1

1

Floating-point operations are inherently imprecise, and most likely the sensor inputs are mapped to 0~1 using some transformation to floating point. I highly doubt your gamepad is sensitive enough for 0.999969482422 to be significantly different from 1 given that the difference, when calculated with Python, is 0.000030517577999988887, which is around 3/100000. Even if your gamepad's analog sticks have a sensor resolution that fine, you're unlikely to get exactly 1 with any joystick. Using exact equality with floating-point operations is a bad idea, and even fuzzy comparisons can be tricky (see https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ if you're okay with reading lots of math). You might as well just round (e.g. round(0.999969482422, 4) == 1.0) if you really need clamping to 1.

JAB
  • 20,783
  • 6
  • 71
  • 80