Pygame: Mouse Specific Axis Detection

2019-07-15 13:03发布

问题:

How can I detect ONLY the X axis, for example?

maus_x = 0
maus_y = 0
pygame.mouse.get_pos(maus_x, maus_y)

while not done:

    for event in pygame.event.get():

    if event.type == pygame.MOUSEMOTION:         
        if maus_x < wx_coord:
            angle += 10

In theory, this "pygame.mouse.get_pos" returns a tuple (x, y). But, I'm defining there a variable to represent the x and y in this tuple. The thing is, when I move the mouse (pygame.MOUSEMOTION), when I do what is written in "maus_x < wx_coord:", it executes the function with the Y axis too. And that makes no sense at all.

"angle +=10" must be executed ONLY when I move the mouse in the x axis. Anyone have any idea of what is happening? :)

回答1:

That's not how function calls work. In your code, maus_x is always 0, since nothing ever modifies it. You want:

while not done:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:      
            mousex, mousey = pygame.mouse.get_pos()   
            if mousex < wx_coord:
                angle += 10

In fact, you probably just want to inspect the event object directly:

while not done:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:      
            mousex, mousey = event.pos   
            if mousex < wx_coord:
                angle += 10

Or better yet:

while not done:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:      
            relx, rely = event.rel   
            if relx != 0:  # x movement
                angle += 10