Uzair Ahmed
Uzair Ahmed

Reputation: 49

pygame - Snap Mouse to Grid

I'm making a little platformer game using pygame, and decided that making a level editor for each level would be easier than typing each blocks' coordinate and size.


I'm using a set of lines, horizontally and vertically to make a grid to make plotting points easier.

Here's the code for my grid:

def makeGrid(surface, width, height, spacing):
    for x in range(0, width, spacing):
        pygame.draw.line(surface, BLACK, (x,0), (x, height))
    for y in range(0, height, spacing):
        pygame.draw.line(surface, BLACK, (0,y), (width, y))

I want the user's mouse to move at 10px intervals, to move to only the points of intersection. Here's what I tried to force the mouse to snap to the grid.

def snapToGrid(mousePos):
    if 0 < mousePos[0] < DISPLAYWIDTH and 0 < mousePos[1] < 700:
        pygame.mouse.set_pos(roundCoords(mousePos[0],mousePos[1]))

(BTW, roundCoords() returns the coordinates rounded to the nearest ten unit.)

(Also BTW, snapToGrid() is called inside the main game loop (while not done))

...but this happens, the mouse doesn't want to move anywhere else.


Any suggestions on how to fix this? If I need to, I can change the grid code too. Thanks a bunch.

P.S. This is using the latest version of PyGame on 64 bit Python 2.7

Upvotes: 2

Views: 1200

Answers (1)

Sorade
Sorade

Reputation: 937

First of all I think you're not far off.

I think the problem is that the code runs quite fast through each game loop, so your mouse doesn't have time to move far before being set to the position return by your function.

What I would have a look into is rather than to pygame.mouse.set_pos() just return the snapped coordinates to a variable and use this to blit a marker to the screen highlighting the intersection of interest (here I use a circle, but you could just blit the image of a mouse ;) ). And hide your actual mouse using pygame.mouse.set_visible(False):

def snapToGrid(mousePos):
    if 0 < mousePos[0] < DISPLAYWIDTH and 0 < mousePos[1] < 700:
        return roundCoords(mousePos[0],mousePos[1])

snap_coord = snapToGrid(mousePos)# save snapped coordinates to variable

pygame.draw.circle(Surface, color, snap_coord, radius, 0)# define the remaining arguments, Surface, color, radius as you need

pygame.mouse.set_visible(False)# hide the actual mouse pointer

I hope that works for you !

Upvotes: 2

Related Questions