【问题标题】:How do i bounce seperate rectangles with list of different coordinates for different Rect Obj in pygame?如何在pygame中为不同的Rect Obj反弹具有不同坐标列表的单独矩形?
【发布时间】:2021-08-21 15:11:33
【问题描述】:

所以,我想要的是移动每个矩形。 该程序正在移动矩形,但其中一些甚至不触及底部、左侧、右侧或顶部。就像只有一个人在决定它们的移动。如何将其更改为与其他矩形不同的移动 这是我的代码

import pygame
from random import randint
 
screen = pygame.display.set_mode((500, 400))
running = True
dx = 0.1
dy = 0.1
rt = []
for i in range(5):
    x = randint(0, 500)
    y = randint(0, 400)
    rt.append([x, y])

def draw_rec(x, y):
    r = pygame.Rect(x, y, 30, 30)  # startx, starty, width, height
    pygame.draw.rect(screen, (255, 255, 255), r)


while running:
    screen.fill((0, 145, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    for i in range(5):
        x = rt[i][0]
        y = rt[i][1]

        if x < 470:
            x += dx
        else:
            dx = -0.1
            x += dx

        if y < 370:
            y += dy
        else:
            dy = -0.1
            y += dy

        if x < 1:
            dx = 0.1
        if y < 1:
            dy = 0.1

        draw_rec(x, y)
        rt[i][0] = x
        rt[i][1] = y

    pygame.display.update()

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    每个矩形都按自己的方向移动。因此 1 个方向向量(dxdy)是不够的。每个矩形都需要一个单独的方向向量。删除dxdy,但添加方向向量列表。

    小例子:

    import pygame
    from random import randint
     
    screen = pygame.display.set_mode((500, 400))
    running = True
    
    d = []
    rt = []
    for i in range(5):
        x = randint(0, 500)
        y = randint(0, 400)
        rt.append([x, y])
        d.append([0.1, 0.1])
    
    def draw_rec(x, y):
        r = pygame.Rect(x, y, 30, 30)  # startx, starty, width, height
        pygame.draw.rect(screen, (255, 255, 255), r)
    
    
    while running:
        screen.fill((0, 145, 0))
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
        for i in range(5):
            x = rt[i][0]
            y = rt[i][1]
    
            if x < 470:
                x += d[i][0]
            else:
                d[i][0] = -0.1
                x += d[i][0]
    
            if y < 370:
                y += d[i][1]
            else:
                d[i][1] = -0.1
                y += d[i][1]
    
            if x < 1:
                d[i][0] = 0.1
            if y < 1:
                d[i][1] = 0.1
    
            draw_rec(x, y)
            rt[i][0] = x
            rt[i][1] = y
    
        pygame.display.update()
    

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      相关资源
      最近更新 更多