如何在pygame中在给定坐标的范围内限制rect对象?

问题描述

我的代码中有一个名为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,则将其更改为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