繁体   English   中英

如何在不更新pygame中的整个屏幕的情况下画一条线?

[英]How do I draw a line without updating the whole screen in pygame?

我正在尝试制作包含移动线和静态背景的视觉表示。 有没有办法在不更新整个屏幕的情况下可视化移动线? 我知道pygame.display.flip()但这需要程序在每一帧中“blit”背景,我想避免这种情况。

我一直在尝试为背景创建一个 rect 对象,为线创建一个对象,然后执行pygame.display.update(line_rect)但我无法找到一种在 rect 中包含一条线的方法。

非常感谢所有的想法!

如果您有一条由点 ( x1 , y1 ) 和 ( x2 , y2 ) 定义的线,则可以使用minmax计算边界矩形:

min_x, min_y = min(x1, x2), min(y1, y2)
max_x, max_y = max(x1, x2), max(y1, y2)
line_rect = pygame.Rect(min_x, min_y, max_x-min_x, max_y-min_y)

另外,您可以加入两个矩形与1x1的大小与union ,以一个完全覆盖提供的两个长方形的区域:

line_rect = pygame.Rect(x1, y1, 1, 1).union((x2, y2, 1, 1))

最小的例子:

import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

center_x, center_y = window.get_rect().center
radius = 100
line_vector = pygame.math.Vector2(1, 0)
angle = 0
prev_line_rect = None

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window_center = window.get_rect().center

    rot_vector = line_vector.rotate(angle) * radius
    x1, y1 = round(center_x + rot_vector.x), round(center_y + rot_vector.y)
    x2, y2 = round(center_x - rot_vector.x), round(center_y - rot_vector.y)
    angle += 1

    line_rect = pygame.Rect(x1, y1, 1, 1).union((x2, y2, 1, 1))
    
    copy_rect = line_rect.copy()
    if prev_line_rect:
        line_rect.union_ip(prev_line_rect)
        line_rect.inflate_ip(2, 2)
    prev_line_rect = copy_rect

    window.fill(0, line_rect)
    pygame.draw.line(window, (255, 255, 255), (x1, y1), (x2, y2), 3)

    pygame.display.update(line_rect)

pygame.quit()
exit()

暂无
暂无

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

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