python - 如何在pygame中添加多个矩形碰撞
问题描述
我想在这个碰撞模拟中添加多个矩形,我不熟悉 OOP,我知道这是解决这个问题的最佳解决方案,以免重复相同的代码。到目前为止,这是我的代码:
import pygame, sys
def bouncing_rect():
global x_speed, y_speed, other_speed
moving_rect.x += x_speed
moving_rect.y += y_speed
#collision with border of screen:
if moving_rect.right >= screen_width or moving_rect.left <= 0:
x_speed = - x_speed
if moving_rect.bottom >= screen_height or moving_rect.top <= 0:
y_speed = - y_speed
# moving the other rect:
other_rect.y += other_speed
if other_rect.top <= 0 or other_rect.bottom >= screen_height:
other_speed = - other_speed
#collision with other rect:
collision_tolerance = 10
if moving_rect.colliderect(other_rect):
if abs(other_rect.top - moving_rect.bottom) < collision_tolerance and y_speed > 0:
y_speed = - y_speed
if abs(other_rect.bottom - moving_rect.top) < collision_tolerance and y_speed < 0:
y_speed = - y_speed
if abs(other_rect.right - moving_rect.left) < collision_tolerance and x_speed < 0:
x_speed = - x_speed
if abs(other_rect.left - moving_rect.right) < collision_tolerance and x_speed > 0:
x_speed = - x_speed
pygame.draw.rect(screen, (255,255,255), moving_rect)
pygame.draw.rect(screen, (255,0,0), other_rect)
pygame.init()
clock = pygame.time.Clock()
screen_width, screen_height = 800,800
screen = pygame.display.set_mode((screen_width, screen_height))
moving_rect = pygame.Rect(50,50,50,50) #(left, top, width, height)
x_speed, y_speed = 5,4
other_rect = pygame.Rect(300,600,200,100)
other_speed = 2
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((30,30,30))
bouncing_rect()
pygame.display.flip()
clock.tick(60)
它还没有使用 OOP。
解决方案
创建一个矩形列表:
other_rect_list = [other_rect1, other_rect2, other_rect3]
使用collidelist()
o 查找列表中与矩形碰撞的第一个矩形的索引:
index = moving_rect.collidelist(other_rect_list)
if index >= 0:
other_rect = other_rect_list[index]
# [...]
或者,您可以使用collidelistall()
获取所有碰撞矩形的索引列表:
index_list = moving_rect.collidelistall(other_rect_list)
for index in index_list:
other_rect = other_rect_list[index]
# [...]
推荐阅读
- ruby-on-rails - 如何回滚此 Rails 迁移?
- javascript - 在从现有阵列中创建新阵列时需要帮助
- firebase - 从 Firebase 云函数调用时,OAuth2 访问令牌交换失败
- c# - 请求响应对象和内容类型注释约定
- flutter - 如何在一个 ListView 中使用多个 StreamBuilder
- c++ - 结转数据而不使用 for 循环
- python - 使用 plt.plot 绘制图表时遇到问题
- laravel - Laravel 日志文件权限问题
- wordpress - 如何仅重写 Wordpress 主页 url?
- python - 模板文件中的静态块标签无效