1 回答
TA贡献1805条经验 获得超9个赞
我建议使用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-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)
添加回答
举报