I am trying to make a game with pygame but I can't figure out how to keep my character from going off screen(set a limit). I have a .png image controlled by user input, but it's possible for the character to go off the visible screen area normally. I can't figure out how to do this. I made a rectangle around the window, (pygame.draw.rect
) but I can't assign the rect to a variable so I can create a collision. I also tried this:
if not character.get_rect() in screen.get_rect():
print("error")
But it didn't work, just spammed the python console with "error" messages.
(i checked the other post with this question but nothing worked/didn't get it)
So my question is, how can I keep my character from going offscreen, and which is the best way to do that?
~thanks
EDIT: My game doesn't have a scrolling playfield/camera. (just a fixed view on the whole window)
I see what you are trying here. If you want to check if a
Rect
is inside another one, usecontains()
:If you simply want to stop the movement on the edges on the screen, an easy solution is to use
clamp_ip()
:Here's a simple example where you can't move the black rect outside the screen:
When you used
pygame.draw.rect
, you didn't actually create a "physical" boundary- you just set the colour of the pixels on the screen in a rectangular shape.If you know the size of the screen, and the displacement of all of the objects on the screen (only applicable if your game has a scrolling playfield or camera), then you can do something like this:
...
Note that a useful tool for you to get the size of the Pygame window is
pygame.display.get_surface().get_size()
which will give you a tuple of the width and height. It is still better, however, to avoid calling this every time you need to know the boundaries of the player. That is, you should store the width and height of the window for later retrieval.Here's a simple control code that I use in my games to keep sprites from going off the screen:
WIDTH and HEIGHT are constants that you define to set the size of your screen. I hope this helps.