1 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
我建議使用pygame.math.Vector2
.
定義直線的中心點(diǎn)、半徑、方向向量和角度
center_x,?center_y?=?SURFACE.get_rect().center radius?=?100line_vector?=?pygame.math.Vector2(1,?0) angle?=?0
由于要逆時(shí)針旋轉(zhuǎn),因此需要在按下鼠標(biāo)按鈕時(shí)減小角度:
if?pygame.mouse.get_pressed()[0]: ????angle?-=?1
用于pygame.math.Vector2.rotate()
旋轉(zhuǎn)方向向量并計(jì)算旋轉(zhuǎn)后的線的起點(diǎn)和終點(diǎn)
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
來(lái)畫(huà)線:
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()
如果您想繞線的起點(diǎn)旋轉(zhuǎn),則不需要中心點(diǎn)。定義行的起點(diǎn):
start_x, start_y = SURFACE.get_rect().center
length = 200
計(jì)算旋轉(zhuǎn)的終點(diǎn):
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)
添加回答
舉報(bào)