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

问题描述

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

解决方法

一般公式为(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,cpt[0] + vec.y
    
    angle += 1     
    if angle >= 360:
        angle = 0

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

pygame.quit()
exit()