我在使用pygame显示对曲面的更改时遇到问题

2024-04-19 08:17:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前的目标是使一个较小的圆围绕一个较大圆的中心旋转,并使矩形沿着较小圆的路径旋转

我创建了一个TargetCircle类,因为当这个可视化完成时,总共有18个圆。 我的问题是,在更改每个圆的theta值并尝试显示更改后,什么都没有发生

目前,所有显示的是横跨顶部的9个圆圈以及水平线和垂直线,但是,所有东西都保持静止。任何帮助都将不胜感激。多谢各位

import pygame as pg
import pygame.gfxdraw
import math

pg.init()
windowWidth = 800
windowHeight = 800
surface = pg.display.set_mode((windowWidth, windowHeight))
pg.display.set_caption("Circle")
clock = pg.time.Clock()
black = (0, 0, 0)
white = (255, 255, 255)
gray = (50, 50, 50)
red = (255, 0, 0)


class TargetCircle(object):
    def __init__(self, posX, posY):
        self.circlePositionX = posX
        self.circlePositionY = posY
        self.radius = 38
        self.theta = 0
        self.x = int((self.circlePositionX + (self.radius * math.cos(self.theta))))
        self.y = int((self.circlePositionY + (self.radius * math.sin(self.theta))))

    def draw(self, win):
        pg.draw.rect(win, gray, (0, self.y, 800, 1))
        pg.draw.rect(win, gray, (self.x, 0, 1, 800))
        pygame.gfxdraw.aacircle(win, self.circlePositionX, self.circlePositionY, self.radius, white)
        pygame.gfxdraw.filled_circle(win, self.x, self.y, 2, white)


circleList = []
x = 120
for i in range(1, 10):
    circle = TargetCircle(x, 40)
    circle.draw(surface)
    circleList.append(circle)
    x += 80
pg.display.update()
loop = 0
run = True
while run:

    clock.tick(160)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            run = False

    if loop == len(circleList):
        loop = 0

    surface.fill(0)
    for i in range(len(circleList)):
        circleList[i].theta += .10
        circleList[i].draw(surface)
    pg.display.flip()
    loop += 1

pg.quit()

1条回答
网友
1楼 · 发布于 2024-04-19 08:17:18

问题是您没有更新TargetCircle的x和y值。你设定

        self.x = int((self.circlePositionX + (self.radius * math.cos(self.theta))))
        self.y = int((self.circlePositionY + (self.radius * math.sin(self.theta))))

__init__中调用一次(在开始时调用一次),然后再也不会设置它。要解决此问题,请将这两行移到TargetCircle.draw(称为每帧):

class TargetCircle(object):
    def __init__(self, posX, posY):
        self.circlePositionX = posX
        self.circlePositionY = posY
        self.radius = 38
        self.theta = 0

    def draw(self, win):
        self.x = int((self.circlePositionX + (self.radius * math.cos(self.theta))))
        self.y = int((self.circlePositionY + (self.radius * math.sin(self.theta))))
        pg.draw.rect(win, gray, (0, self.y, 800, 1))
        pg.draw.rect(win, gray, (self.x, 0, 1, 800))
        pygame.gfxdraw.aacircle(win, self.circlePositionX, self.circlePositionY, self.radius, white)
        pygame.gfxdraw.filled_circle(win, self.x, self.y, 2, white)

相关问题 更多 >