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

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


小怪兽爱吃肉
浏览 150回答 1
1回答

Cats萌萌

我建议使用pygame.math.Vector2.定义直线的中心点、半径、方向向量和角度center_x, center_y = SURFACE.get_rect().center radius = 100line_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)使用start和end来画线:pygame.draw.line(SURFACE, (5,80,255), start, end, 8)最小示例: repl.it/@Rabbid76/PyGame-VectorRotateLineimport sys, pygamefrom math import sin, cos, radians, pifrom pygame.locals import QUIT, MOUSEBUTTONDOWNpygame.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().centerlength = 200计算旋转的终点:rot_vector = line_vector.rotate(angle) * lengthstart = start_x, start_yend = round(start_x + rot_vector.x), round(start_y + rot_vector.y)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python