pygame - 尝试移动矩形

1 投票
1 回答
532 浏览
提问于 2025-04-18 07:28

我正在制作一个鼓游戏(基于dtx-Mania)。

我遇到了一个问题,就是如何画一个矩形并让它移动。我可以画一个静止的矩形,但无法让它动起来。目前我用了一条线,但看起来pygame把它当成了矩形。如果有影响的话,我会改回矩形。

我的目标是画出这个矩形,并让它以足够慢的速度移动,大约需要1秒钟才能到达一条线。

我知道我还有很多东西要学习,这就是我目前测试的结果。

#!/usr/bin/env python3
#-*- coding:utf-8 -*-
#small exemple of a moving rectangle
import pygame, sys
pygame.init()
fpsClock = pygame.time.Clock()
windowsSurfaceObj = pygame.display.set_mode((640, 480))
pygame.display.set_caption('moving rectangle test')
white = pygame.Color(255, 255, 255)
black = pygame.Color(0, 0, 0)
step = pygame.draw.line(windowsSurfaceObj, white, (233, 0), (269, 0), 6)
step
while True:
    windowsSurfaceObj.fill(black)
    #the coordonate are moved but the rectangle is now drew
    step.move(0, -1)
    #this is the target line (where the moving object must go to)
    pygame.draw.line(windowsSurfaceObj, white, (90, 420), (390, 420), 6)
    pygame.display.update()
    fpsClock.tick(30)

谢谢你的帮助。

1 个回答

0

阅读文档总是个好主意。来自pygame文档的内容:

line(Surface, color, start_pos, end_pos, width=1) -> Rect

在一个表面上画一条直线。线的两端是方形的,没有圆头,特别是当线条比较粗的时候。

在整个模块的描述中:

The functions return a rectangle representing the bounding area of changed pixels.

所以你画了第一条线,然后移动一个矩形,这个矩形代表了改变的像素区域。因为你没有重新绘制这条线,所以你的第一条线就消失了。

为了解决这个问题,你需要在移动后,在循环中重新画这条线。

step.move(0, -1)
pygame.draw.rect(windowsSurfaceObj, white,step, 6)

撰写回答