【问题标题】:Pygame: colliding rectangles with other rectangles in the same listPygame:将矩形与同一列表中的其他矩形碰撞
【发布时间】:2019-07-14 14:04:44
【问题描述】:

我有 10 个受重力影响的绘制矩形列表(在我的脚本中称为立方体)。我制作了一个简单的碰撞系统,让他们在撞到地面时停下来。我怎样才能让它在 2 个立方体碰撞时停止下落,就像它们与地面一样?

import pygame
import time
import random
pygame.init()
clock = pygame.time.Clock()
wnx = 800
wny = 600
black = (0,0,0)
grey = (75,75,75)
white = (255,255,255)
orange = (255,100,30)
wn = pygame.display.set_mode((wnx, wny))
wn.fill(white)
def cube(cx,cy,cw,ch):
    pygame.draw.rect(wn, orange, [cx, cy, cw, ch])
def floor(fx,fy,fw,fh):
    pygame.draw.rect(wn, grey, [fx, fy, fw, fh])
def main():
    floory = 550    
    number = 30
    cubex = [0] * number
    cubey = [0] * number
    cubew = 10                          
    cubeh = 10
    for i in range(len(cubex)):
        cubex[i] = (random.randrange(0, 80)*10)
        cubey[i] = (random.randrange(2, 5)*10)
    gravity = -10
    exit = False

    while not exit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit = True
        for i in range(len(cubex)): #i want to check here if it collides with an other cube
            if not (cubey[i] + 10) >= floory:
                cubey[i] -= gravity

        wn.fill(white)
        floor(0,floory,800,50)

        for i in range(len(cubex)):
            cube(cubex[i], cubey[i], cubew, cubeh)

        pygame.display.update()
        clock.tick(5)
main()
pygame.quit()
quit()

【问题讨论】:

    标签: python arrays python-3.x python-2.7 pygame


    【解决方案1】:

    使用pygame.Rect.colliderect 检查矩形是否相交。

    创建一个矩形 (pygame.Rect),定义立方体的下一个位置(区域):

    cubeR = pygame.Rect(cubex[i], cubey[i] + 10, cubew, cubeh)
    

    查找所有相交的矩形

    cl = [j for j in range(len(cubey)) if j != i and cubeR.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
    

    如果发生any() 碰撞,请不要移动(让进一步“下落”)立方体:

    if not any(cl):
        # [...]
    

    检查可能如下所示:

    for i in range(len(cubex)):
        cubeR = pygame.Rect(cubex[i], cubey[i] + 10, cubew, cubeh)
        cisect = [j for j in range(len(cubey)) if j != i and cubeR.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
        if not any(cisect) and not (cubey[i] + 10) >= floory:
            cubey[i] -= gravity
    

    注意,由于所有立方体都与 10*10 光栅对齐,因此检查立方体的原点是否相等就足够了:

    for i in range(len(cubex)):
        cisect = [j for j in range(len(cubey)) if j != i and cubex[i] == cubex[j] and cubey[i]+10 == cubey[j]]
        if not any(cisect) and not (cubey[i] + 10) >= floory:
            cubey[i] -= gravity
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多