Pygame Vector2.as_polar()和Vector2.from_polar()方法

时间:2017-07-31 15:46:39

标签: python vector pygame azimuth

有人可以告诉我一个使用Vector2.as_polar()获取距离和方位角的示例,然后将该信息重新插入Vector2.from_polar()以获取笛卡尔坐标吗?

假设我们想要(0, 0)(15, 10)之间的距离和方位角,然后将该信息插入Vector2.from_polar()以再次生成(15, 10)

我会准确地解释我在做什么,但我和其他所有人都可以更容易地看到一个有效的例子。

1 个答案:

答案 0 :(得分:1)

您可以将矢量定义为半径和角度 - 极坐标。

让我们使用屏幕中心的点矢量作为极坐标系的极点

pole = Vector2(screen_rect.center)

要在from_polar方法的帮助下设置矢量的坐标,首先定义一个矢量,然后传递一个由半径和角度组成的元组:

vec = Vector2()
# This updates the cartesian coordinates of vec.
vec.from_polar((90, 60))  # 90 pixels long, rotated 60 degrees.

然后使用pygame.draw.line绘制它(将vec添加到pole以获取目标坐标):

pg.draw.line(screen, (200, 90, 20), pole, pole+vec, 3)

作为as_polar的演示,计算到鼠标位置的向量,并将极坐标解压缩到我们稍后渲染的变量rphi,以查看当前的半径和角度这个载体。

r, phi = (mouse_pos-pole).as_polar()

请注意,pygame的y轴被翻转,因此负角度指向上方,正角度指向下方。

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()

这是另一个跟随鼠标的精灵的例子(按“w”或“s”加速)。我将self.speed作为半径和as_polar作为参数返回的角度传递给from_polar以设置玩家精灵的vel个星期。

import sys
import pygame as pg


class Player(pg.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((50, 30), pg.SRCALPHA)
        color = pg.Color('dodgerblue1')
        pg.draw.polygon(self.image, color, ((1, 1), (49, 15), (1, 29)))
        self.orig_img = self.image
        self.rect = self.image.get_rect(center=pos)
        self.pos = pg.math.Vector2(pos)
        self.vel = pg.math.Vector2(0, 0)
        self.speed = 0

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.center = self.pos

    def rotate(self):
        _, angle = (pg.mouse.get_pos()-self.pos).as_polar()
        self.vel.from_polar((self.speed, angle))
        self.image = pg.transform.rotozoom(self.orig_img, -angle, 1)
        self.rect = self.image.get_rect(center=self.rect.center)


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    player = Player((300, 200))
    all_sprites.add(player)

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        keys = pg.key.get_pressed()
        if keys[pg.K_w]:
            player.speed += .2
        elif keys[pg.K_s]:
            player.speed -= .2

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()