pygame rotating a line

2020-02-14 08:19发布

问题:

I am trying to create a "radar" in Pygame. I am having trouble rotating the needle of the radar. How do I rotate it?

import pygame
from pygame.locals import *
SIZE = 800, 800
pygame.init()
screen = pygame.display.set_mode(SIZE)
FPSCLOCK = pygame.time.Clock()
done = False
screen.fill((0, 0, 0))
degree=0
while not done:
    for e in pygame.event.get():
        if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
            done = True
            break
    for x in range(1,400,10):
        pygame.draw.circle(screen,(255,255,255),(400,400),x,1)
    line = pygame.draw.line(screen,(10,100,10),(400,400),(400,0),3)
    pygame.transform.rotate(line,degree)
        pygame.display.flip()   
        degree+=5
        FPSCLOCK.tick(40)

回答1:

You need to calculate your start and end position.

import math
import pygame
from pygame.locals import *

radar = (100,100)
radar_len = 50
x = radar[0] + math.cos(math.radians(angle)) * radar_len
y = radar[1] + math.sin(math.radians(angle)) * radar_len

# then render the line radar->(x,y)
pygame.draw.line(screen, Color("black"), radar, (x,y), 1)


回答2:

You can also just use vectors, one for the "startpoint", one for the endpoint (that's the offset from the startpoint) and then rotate the endpoint vector and add it to the startpoint.

import sys
import pygame

pygame.init()

screen = pygame.display.set_mode((640, 480))
FPSCLOCK = pygame.time.Clock()
RED = pygame.Color("red")
startpoint = pygame.math.Vector2(320, 240)
endpoint = pygame.math.Vector2(170, 0)
angle = 0
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # % 360 to keep the angle between 0 and 360.
    angle = (angle+5) % 360
    # The current endpoint is the startpoint vector + the
    # rotated original endpoint vector.
    current_endpoint = startpoint + endpoint.rotate(angle)

    screen.fill((0, 0, 0))
    pygame.draw.line(screen, RED, startpoint, current_endpoint, 2)

    pygame.display.flip()
    FPSCLOCK.tick(30)

pygame.quit()
sys.exit()


标签: python pygame