首页 > 解决方案 > 控制椭圆路径周围的旋转时间 - 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, 0))
        pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
        pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
        pygame.draw.ellipse(screen, (255, 0, 255), [200, 100, 200, 100], 1)
        pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
        pygame.draw.circle(screen, (255, 0, 255), [x2, y2], 5)

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

标签: pythonpygame

解决方案


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

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

添加 2 个变量degree1degree2然后每帧将它们增加不同的数量。增加degree14 和degree21

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, 0))
    pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
    pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
    pygame.draw.ellipse(screen, (255, 0, 255), [200, 100, 200, 100], 1)
    pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
    pygame.draw.circle(screen, (255, 0, 255), [x2, y2], 5)

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

推荐阅读