如何在 PyGame 中找到圆上点的坐标?

时间:2021-04-21 14:21:05

标签: python math pygame

如果精灵位于 pygame 中点 250,250 处的圆的中心,那么在相对于原始点的任何方向上找到圆的边缘的等式是什么。方程中是否有角度(如 X)?

1 个答案:

答案 0 :(得分:3)

一般公式为(x, y) = (cx + r * cos(a), cy + r * sin(a))

但是,在您的情况下,° 位于顶部,并且角度顺时针增加。因此公式为:

angle_rad = math.radians(angle)
pt_x = cpt[0] + radius * math.sin(angle_rad)
pt_y = cpt[1] - radius * math.cos(angle_rad)  

或者,您可以使用 pygame.math 模块和 pygame.math.Vector2.rotate

vec = pygame.math.Vector2(0, -radius).rotate(angle)
pt_x, pt_y = cpt[0] + vec.x, cpt[0] + vec.y

最小示例:

import pygame
import math

pygame.init()
window = pygame.display.set_mode((500, 500))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()
cpt = window.get_rect().center
angle = 0
radius = 100

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False  

    # solution 1
    #angle_rad = math.radians(angle)
    #pt_x = cpt[0] + radius * math.sin(angle_rad)
    #pt_y = cpt[1] - radius * math.cos(angle_rad)    
    
    # solution 2
    vec = pygame.math.Vector2(0, -radius).rotate(angle)
    pt_x, pt_y = cpt[0] + vec.x, cpt[0] + vec.y
    
    angle += 1     
    if angle >= 360:
        angle = 0

    window.fill((255, 255, 255))
    pygame.draw.circle(window, (0, 0, 0), cpt, radius, 2)
    pygame.draw.line(window, (0, 0, 255), cpt, (pt_x, pt_y), 2)
    pygame.draw.line(window, (0, 0, 255), cpt, (cpt[0], cpt[1]-radius), 2)
    text = font.render(str(angle), True, (255, 0, 0))
    window.blit(text, text.get_rect(center = cpt))
    pygame.display.flip()

pygame.quit()
exit()