Pygame - 如何阻止精灵离开窗口边缘?

imr*_*mes 2 python pygame

我的窗口弹出,我可以用箭头键在屏幕上移动我的精灵.我知道在sprite碰撞中有sprite的碰撞功能,但我似乎无法弄清楚如何阻止它们移动到可见区域之外.有什么想法吗?

我的移动功能:

def moveme(self,coords)
    #coords=(x,y)
    self.rect.move_ip(coords)
Run Code Online (Sandbox Code Playgroud)

对于事件处理程序我正在使用类似的东西

keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
    character.moveme((0, -4))
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

Bar*_*ski 5

移动后使用clamp_ip怎么样?

Rect.clamp_ip(Rect): return None
Run Code Online (Sandbox Code Playgroud)

它需要一个Rectangle,在你的情况下是你的窗口元组.

所以你的代码看起来像这样:

screen_rect = pygame.Rect((0, 0), (700, 400))

def moveme(self,x,y):
    self.rect.move_ip((x,y))
    self.rect.clamp_ip(screen_rect)
Run Code Online (Sandbox Code Playgroud)