import sys
import pygame as pg
from pygame.math import Vector2
def main():
screen = pg.display.set_mode((640, 480))
screen_rect = screen.get_rect()
font = pg.font.Font(None, 30)
color = pg.Color(150, 250, 100)
clock = pg.time.Clock()
pole = Vector2(screen_rect.center)
# A zero vector.
vec = Vector2()
# To set the coordinates of `vec` we can pass the
# polar coordinates (radius, angle) to `from_polar`.
vec.from_polar((90, 60))
print(vec) # Now take a look at the updated cartesian coordinates.
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
mouse_pos = pg.mouse.get_pos()
# `as_polar` gives us the radius and angle of the vector that
# points to the mouse. Unpack it into the `r` and `phi` variables.
r, phi = (mouse_pos-pole).as_polar()
screen.fill((30, 30, 30))
# Draw the line to the mouse pos.
pg.draw.line(screen, color, pole, mouse_pos, 3)
# Add the vec to the pole to get the target coordinates.
pg.draw.line(screen, (200, 90, 20), pole, pole+vec, 3)
# Render the radius and angle.
txt = font.render('r: {:.1f}'.format(r), True, color)
screen.blit(txt, (30, 30))
txt = font.render('phi: {:.1f}'.format(phi), True, color)
screen.blit(txt, (30, 50))
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
可以将向量定义为半径和角度-极坐标。在
让我们使用屏幕中心的点向量作为极坐标系的极。在
要使用
^{pr2}$from_polar
方法设置向量的坐标,首先定义一个向量,然后传递一个由半径和角度组成的元组:然后使用
pygame.draw.line
绘制它(将vec
添加到pole
以获得目标坐标):作为}中,我们稍后将呈现这些变量,以查看该向量的当前半径和角度。在
as_polar
的演示,计算鼠标位置的向量,并将极坐标解压到变量r
和{请注意,pygame的y轴是翻转的,因此负角指向上,正角向下。在
下面是另一个例子,在鼠标后面有一个精灵(按“w”或“s”加速)。我传递
self.speed
作为半径,as_polar
返回的角度作为from_polar
的参数,以设置玩家精灵的vel
社区。在相关问题 更多 >
编程相关推荐