如何在 pygame 中将矩形对象限制在给定坐标的边距内?

How to restrict a rect object in a margin of given co-ordinates in pygame?

我的代码中有一个名为 ball_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