Python Pygame-中心轴旋转线段

问题描述

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))

        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()

我正在尝试编写一条绕中心轴逆时针旋转的线段。很难理解。终端位置部分对我来说很难。

解决方法

我建议使用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))
        pygame.draw.line(SURFACE,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)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...