Python pygame - 中心轴旋转线段

Python pygame - center axis rotation segment line

import sys, pygame
from math import sin, cos, radians, pi
from pygame.locals import QUIT, MOUSEBUTTONDOWN

pygame.init()
SURFACE = pygame.display.set_mode((780,920))
FPSCLOCK = pygame.time.Clock()

def Line():
    speed = 0

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

        if pygame.mouse.get_pressed() [0]:
            speed += 26
            if speed > 60:
                speed = 60

        else:
            speed -= 15
            if speed < 0:
                speed = 0

        SURFACE.fill((255,0,0))

        radius = speed * 0.8
        
        pygame.draw.line(SURFACE,(5,80,255),(295,127),(sin(200-radius),cos(300-radius)),8)
        pygame.display.update()
        FPSCLOCK.tick(6)

if __name__ == '__main__' :
    Line()

我正在尝试编写一条绕中心轴逆时针旋转的线段。这很难理解。 end-pos部分对我来说很难。

我建议使用 pygame.math.Vector2

定义圆心、半径、直线的方向向量和角度

center_x, center_y = SURFACE.get_rect().center
radius = 100
line_vector = pygame.math.Vector2(1, 0)
angle = 0

由于要逆时针旋转,需要在按下鼠标键时减小角度:

if pygame.mouse.get_pressed()[0]:
    angle -= 1

使用pygame.math.Vector2.rotate()旋转方向向量并计算旋转后的直线起点和终点

rot_vector = line_vector.rotate(angle) * radius
start = round(center_x + rot_vector.x), round(center_y + rot_vector.y)
end = round(center_x - rot_vector.x), round(center_y - rot_vector.y)

使用startend画线:

pygame.draw.line(SURFACE, (5,80,255), start, end, 8)

最小示例: repl.it/@Rabbid76/PyGame-VectorRotateLine

完整示例:

import sys, pygame
from math import sin, cos, radians, pi
from pygame.locals import QUIT, MOUSEBUTTONDOWN
pygame.init()
SURFACE = pygame.display.set_mode((780,920))
FPSCLOCK = pygame.time.Clock()

def Line():
    center_x, center_y = SURFACE.get_rect().center
    radius = 100
    line_vector = pygame.math.Vector2(1, 0)
    angle = 0
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        if pygame.mouse.get_pressed()[0]:
            angle -= 1
            print(angle)
        
        rot_vector = line_vector.rotate(angle) * radius
        start = round(center_x + rot_vector.x), round(center_y + rot_vector.y)
        end = round(center_x - rot_vector.x), round(center_y - rot_vector.y)
       
        SURFACE.fill((255,0,0))
        pygame.draw.line(SURFACE, (5,80,255), start, end, 8)
        pygame.display.update()
        FPSCLOCK.tick(60)

if __name__ == '__main__' :
    Line()

如果要绕直线的起点旋转,则不需要中心点。定义行首:

start_x, start_y = SURFACE.get_rect().center
length = 200

计算旋转终点:

rot_vector = line_vector.rotate(angle) * length
start = start_x, start_y
end = round(start_x + rot_vector.x), round(start_y + rot_vector.y)