Question

I have been experimenting with Pygame, and have come across a problem that I could not find the answer to. In this paste, my basic game framework is exhibited. How can i complete my ballSnapLeft() definition correctly?

Edit: I am not looking for my code to be completed, but I am looking for someone to explain how the 'Rect' class(?) works, and how it could be applied.

Edit2: I have tried to use the x and y coordinates to do so, but I think there is a simpler way that can actually work, instead of using brute coordinates.

Was it helpful?

Solution

From Making Games With Python and Pygame:

myRect.left The int value of the X-coordinate of the left side of the rectangle.

myRect.right The int value of the X-coordinate of the right side of the rectangle.

myRect.top The int value of the Y-coordinate of the top side of the rectangle.

myRect.bottom The int value of the Y-coordinate of the bottom side.

Because all of these attributes return integers, that's probably why your code isn't working.

Also, if your goal with ballSnapLeft() is to move the ball to a position away from the player, ballRect.right = playerRect.left - distance would only change the X coordinate of the rect. To make the ball also move in the Y coordinate you could do something like

def ballSnapTop():
    ballRect.top = playerRect.bottom - distance

OTHER TIPS

Are you getting an error when you execute ballRect.right = playerRect.left - (0, 1)?

ballRect.right and ballRect.left, along with the related top, bottom, width, height values, are int types and can't have tuples added or subtracted from them.

You might want to take a look at the pygame.Rect documentation, and consider using pygame.Rect.move(x,y) which will shift the coordinates of the rectangle for you.

It's also worth noting that if you change, for example, myRect.topleft, then the corresponding top, left, bottom, etc... values will change as well so that the rect translates and preserves its size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top