Skip to main content
 首页 » 编程设计

python之如何使用 Pygame 矩形

2025年05月04日16shihaiming

我一直在试验 Pygame,遇到了一个我找不到答案的问题。在 this paste ,展示了我的基本游戏框架。我怎样才能正确完成我的 ballSnapLeft() 定义?

编辑:我不是在寻找要完成的代码,而是在寻找可以解释“Rect”类(?)如何工作以及如何应用它的人。

Edit2:我曾尝试使用 x 和 y 坐标来这样做,但我认为有一种更简单的方法可以实际工作,而不是使用粗略的坐标。

请您参考如下方法:

来自 Making Games With Python and Pygame :

myRect.left The int value of the X-coordinate of the left side of the rectangle.

myRect.right The int value of the X-coordinate of the right side of the rectangle.

myRect.top The int value of the Y-coordinate of the top side of the rectangle.

myRect.bottom The int value of the Y-coordinate of the bottom side.

因为所有这些属性都返回整数,这可能就是您的代码无法正常工作的原因。

此外,如果您使用 ballSnapLeft() 的目标是将球移动到远离玩家的位置,则 ballRect.right = playerRect.left - distance 只会更改矩形的 X 坐标。要使球也在 Y 坐标上移动,您可以做类似的事情

def ballSnapTop(): 
    ballRect.top = playerRect.bottom - distance