Reputation: 1
I have made an object controlled with arrow keys. When I move it to the edge of the pygame screen, the object moves off the screen. I was wondering how to keep the object on the screen. Any suggestions?
Upvotes: 0
Views: 397
Reputation: 7501
last = player.rect.copy()
player.update()
if not screen.get_rect().contains(player.rect):
player.rect = last
Upvotes: 0
Reputation: 8045
Do something like this:
if player.x == #edge of screen:
player.x -= 0
if player.y == #edge of screen:
player.y -= 0
player.x
being the players current x position and player.y
being the players current y position or you can do the same thing but when the player goes of the screen it automatically goes to the other side of the screen it will probably take some tweaking to get it to look perfect
Upvotes: 0
Reputation: 490163
On each handle of the input, check if the object's target x position plus its width exceeds the width of the canvas or if it is less than 0
. Deny the movement if so.
Repeat for the y coordinate and the height.
Upvotes: 1