Python - Pygame:“窦上方形的坐标”

时间:2017-04-03 21:47:09

标签: python pygame sin cos

我对这段代码有问题,因为我想要4个点(这是圆圈)来制作正方形的顶点,但我不知道这些顶点之间应该有什么区别(变量“更改”)。我把这个变量留空了,拜托,你能给我一些值,我应该插入那里并解释原因吗?

以下是代码:

import pygame
from math import sin, cos

pygame.init()

screen = pygame.display.set_mode((800,600))

BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (0,0,255)
GRAY = (175,175,175)

clock = pygame.time.Clock()
Font = pygame.font.SysFont(None, 50)

angle = 0
angle_c = 0
ex = False

a = (0,0)
b = (0,0)
c = (0,0)
d = (0,0)

change = 

size = 95

x_c = 400
y_c = 200

while not ex:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             ex = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                angle_c = 0.05
            if event.key == pygame.K_RIGHT:
                angle_c = -0.05
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
                angle_c = 0

    angle += angle_c

    a = (round(sin(angle)*size+x_c), round(cos(angle)*size+y_c))
    b = (round(sin(angle+change)*size+x_c), round(cos(angle+change)*size+y_c))
    c = (round(sin(angle+change*2)*size+x_c), round(cos(angle+change*2)*size+y_c))
    d = (round(sin(angle+change*3)*size+x_c), round(cos(angle+change*3)*size+y_c))

    screen.fill(WHITE)

    pygame.draw.circle(screen, BLUE, (400,200), round(sin(360)*100), 3)
    pygame.draw.circle(screen, BLUE, a, 10)
    pygame.draw.circle(screen, WHITE, a, 8)

    pygame.draw.circle(screen, BLUE, b, 10)
    pygame.draw.circle(screen, WHITE, b, 8)

    pygame.draw.circle(screen, BLUE, c, 10)
    pygame.draw.circle(screen, WHITE, c, 8)

    pygame.draw.circle(screen, BLUE, d, 10)
    pygame.draw.circle(screen, WHITE, d, 8)

    pygame.display.update()

    clock.tick(50)


pygame.quit()

1 个答案:

答案 0 :(得分:1)

从正方形中心到正方形顶点的角度相差90度,或pi / 2弧度(这是Python的sincos函数所期望的单位)。< / p>

因此,您可以change变量设置为pi / 2(将pi添加到要从{{1}导入的名称列表之后}模块),你的代码可能会工作。

但是计算坐标比计算坐标更容易,因为旋转90度会以可预测的方式改变正弦和余弦值:

  • mathsin(a + pi/2)
  • cos(a)cos(a + pi/2)

重复应用此转换可以让您在进一步旋转后确定正弦和余弦应该是什么。

您只需要分别拨打-sin(a)sin,然后就可以使用这些值来查找所有坐标。

cos

请注意,在上面的代码中,我遵循数学约定,角度从正y = round(sin(angle) * size) x = round(cos(angle) * size) a = ( x + x_c, y + y_c) b = (-y + x_c, x + y_c) c = (-x + x_c, -y + y_c) d = ( y + x_c, -x + y_c) - 轴开始为零,并随着您最初开始向正x轴旋转而增加(其中将在pygame的坐标系中顺时针方向)。您之前的代码似乎是从正y - 轴测量角度,而在相反方向上增加。如果这是您真正想要的,您只需在初始分配中反转yx(将余弦指定为y,将正弦指定为y)。