控制围绕椭圆路径的旋转时间 - Pygame

问题描述

我需要以比粉红色圆圈快 4 倍的速度旋转蓝色圆圈。 有人可以建议我这样做的方法吗?

现在两个圆圈(粉色和蓝色)都围绕图中所示椭圆路径中的红色圆圈旋转。

这是我的代码

#Elliptical orbits

import pygame
import math
import sys

pygame.init()
screen = pygame.display.set_mode((1000,300))
pygame.display.set_caption("Elliptical orbit")
clock = pygame.time.Clock()

while(True):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    xRadius = 250
    yRadius = 100
    x2Radius = 100
    y2Radius = 50

    for degree in range(0,360,10):
        x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300
        y1 = int(math.sin(degree * 2 * math.pi / 360) * yRadius) + 150
        x2 = int(math.cos(degree * 2 * math.pi / 360) * x2Radius) + 300
        y2 = int(math.sin(degree * 2 * math.pi / 360) * y2Radius) + 150
        screen.fill((0,0))
        pygame.draw.circle(screen,(255,0),[300,150],35)
        pygame.draw.ellipse(screen,255,255),[50,50,500,200],1)
        pygame.draw.ellipse(screen,[200,100,200,100],1)
        pygame.draw.circle(screen,(0,[x1,y1],15)
        pygame.draw.circle(screen,[x2,y2],5)

        pygame.display.flip()
        clock.tick(5)

解决方法

不要通过应用程序循环中的额外循环来控制游戏。使用应用程序循环。请注意,您必须在 for 循环中处理事件。分别见pygame.event.get() pygame.event.pump()

对于游戏的每一帧,您都需要对事件队列进行某种调用。这可确保您的程序可以在内部与操作系统的其余部分进行交互。

添加 2 个变量 degree1degree2,并在每一帧以不同的量增加它们。将 degree1 增加 4 并将 degree2 增加 1

degree1 = (degree1 + 4) % 360
degree2 = (degree2 + 1) % 360

另外增加每秒帧数以获得更流畅的动画:

clock.tick(50)

import pygame,math,sys
pygame.init()
screen = pygame.display.set_mode((1000,300))
pygame.display.set_caption("Elliptical orbit")
clock = pygame.time.Clock()

degree1 = 0
degree2 = 0
while(True):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    xRadius = 250
    yRadius = 100
    x2Radius = 100
    y2Radius = 50

    degree1 = (degree1 + 4) % 360
    degree2 = (degree2 + 1) % 360
    x1 = int(math.cos(degree1 * 2 * math.pi / 360) * xRadius) + 300
    y1 = int(math.sin(degree1 * 2 * math.pi / 360) * yRadius) + 150
    x2 = int(math.cos(degree2 * 2 * math.pi / 360) * x2Radius) + 300
    y2 = int(math.sin(degree2 * 2 * math.pi / 360) * y2Radius) + 150
    screen.fill((0,0))
    pygame.draw.circle(screen,(255,0),[300,150],35)
    pygame.draw.ellipse(screen,255,255),[50,50,500,200],1)
    pygame.draw.ellipse(screen,[200,100,200,100],1)
    pygame.draw.circle(screen,(0,[x1,y1],15)
    pygame.draw.circle(screen,[x2,y2],5)

    pygame.display.flip()
    clock.tick(50)
,

简单来说,只需将蓝色圆圈的度数乘以 4:

x1 = int(math.cos(degree * 4 * 2 * math.pi / 360) * xRadius) + 300
y1 = int(math.sin(degree * 4 * 2 * math.pi / 360) * yRadius) + 150