微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。