繁体   English   中英

Pygame:将矩形与同一列表中的其他矩形碰撞

[英]Pygame: colliding rectangles with other rectangles in the same list

我有一个受重力影响的 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()

使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM