在pygame中,如何将矩形对象限制在给定坐标的范围内



我的代码中有一个名为ball_rect的rect对象,该对象的纵坐标每秒减少2,最终它下降并到达屏幕底部并消失。我希望这个物体在y轴上不超过200个像素。

我也知道这样做的命令,但我忘了。

这是代码:

ball_y = 20
ball_x = 100
ball = pygame.image.load("data/ball.png")
ball_rect = ball.get_rect(topleft = (ball_x,ball_y)
def ball_area(): #here I want to put the code to restrict it in the margin of the screen

您必须测试球矩形的底部是否低于200。如果低于,则将其更改为200。使用新的球顶部矩形更新ball_y

def ball_area():
global ball_x, ball_y
ball_rect = ball.get_rect(topleft = (ball_x, ball_y)
if ball_rect.bottom > 200:
ball_rect.bottom = 200
ball_y = ball_rect.top

最新更新