簡體   English   中英

如何在 pygame 中將三角形旋轉到某個角度?

[英]How to rotate a triangle to a certain angle in pygame?

我需要在屏幕中心旋轉一個三角形(不是圖像)。 我見過其他人回答這個問題,但三角形不能向上。

我曾嘗試使用其他人的功能,但他們認為只能部分工作,例如我上面提到的 function。

import pygame
disp=pygame.display.set_mode((200,200))
import math
def rotate_triange(mouse_pos,triangle_pos):
    #The code here
import time
while True:
    time.sleep(1)
    pygame.Surface.fill(disp,(255,255,255))
    center = (100,100)
    radius = 10
    mouse_position = pygame.mouse.get_pos()
    for event in pygame.event.get():
            pass 
    points = rotate_triangle((100,100),mouse_position)
    pygame.draw.polygon(disp,(0,0,0),points)
    pygame.display.update()

在 pygame 中,二維向量算術在pygame.math.Vector2中實現。

為鼠標 position 和三角形的中心定義一個Vector2 object。 計算向量從中心點到鼠標 position 的角度( .angle_to() ):

vMouse  = pygame.math.Vector2(mouse_pos)
vCenter = pygame.math.Vector2(center)
angle   = pygame.math.Vector2().angle_to(vMouse - vCenter)

圍繞 (0, 0) 定義三角形的 3 個點並將它們旋轉角度(.rotate()

points = [(-0.5, -0.866), (-0.5, 0.866), (2.0, 0.0)]
rotated_point = [pygame.math.Vector2(p).rotate(angle) for p in points]

要計算最終點,這些點必須按三角形中心進行縮放和平移:

triangle_points = [(vCenter + p*scale) for p in rotated_point]

請參閱示例:

import pygame
import math

def rotate_triangle(center, scale, mouse_pos):

    vMouse  = pygame.math.Vector2(mouse_pos)
    vCenter = pygame.math.Vector2(center)
    angle   = pygame.math.Vector2().angle_to(vMouse - vCenter)

    points = [(-0.5, -0.866), (-0.5, 0.866), (2.0, 0.0)]
    rotated_point = [pygame.math.Vector2(p).rotate(angle) for p in points]

    triangle_points = [(vCenter + p*scale) for p in rotated_point]
    return triangle_points

disp=pygame.display.set_mode((200,200))

run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    mouse_position = pygame.mouse.get_pos()
    points = rotate_triangle((100, 100), 10, mouse_position)

    pygame.Surface.fill(disp, (255,255,255))
    pygame.draw.polygon(disp, (0,0,0), points)
    pygame.display.update()

該算法的一個版本,沒有使用pygame.math.Vector2 ,如下所示:

def rotate_triangle(center, scale, mouse_pos):

    dx = mouse_pos[0] - center[0]
    dy = mouse_pos[1] - center[1]
    len = math.sqrt(dx*dx + dy*dy)
    dx, dy = (dx*scale/len, dy*scale/len) if len > 0 else (1, 0)

    pts = [(-0.5, -0.866), (-0.5, 0.866), (2.0, 0.0)]
    pts = [(center[0] + p[0]*dx + p[1]*dy, center[1] + p[0]*dy - p[1]*dx) for p in pts]
    return pts

請注意,此版本可能更快。 與前一種算法的.angle_to()math.sin可能分別使用的math.cos可能由.rotate() () 使用的math.atan2相比,它需要一個math.sqrt操作。 結果坐標相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM