Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将PyGame 2轴操纵杆浮动转换为360度_Python_Pygame_Axis_Angle - Fatal编程技术网

Python 将PyGame 2轴操纵杆浮动转换为360度

Python 将PyGame 2轴操纵杆浮动转换为360度,python,pygame,axis,angle,Python,Pygame,Axis,Angle,我想将我的操纵杆的两个轴浮动(水平和垂直)转换为360度,可用于在我的游戏中设置玩家方向。从我的研究中,我发现最好的方法是使用Atan2 变量: self.rot = 0 horaxis = joy1.get_axis(0) veraxis = joy1.get_axis(1) 演示图:您是正确的,它是用MS Paint绘制的 当然,任何关于代码的建议/片段都将是惊人的 您只需使用轴创建实例,然后调用其as_polar方法来获取角度(请参见)。可以通过以下方式将角度映射到0-360度: im

我想将我的操纵杆的两个轴浮动(水平和垂直)转换为360度,可用于在我的游戏中设置玩家方向。从我的研究中,我发现最好的方法是使用Atan2

变量:

self.rot = 0
horaxis = joy1.get_axis(0)
veraxis = joy1.get_axis(1)
演示图:您是正确的,它是用MS Paint绘制的


当然,任何关于代码的建议/片段都将是惊人的

您只需使用轴创建实例,然后调用其
as_polar
方法来获取角度(请参见)。可以通过以下方式将角度映射到0-360度:

import pygame as pg
from pygame.math import Vector2


def main():
    pg.init()
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    player_img = pg.Surface((42, 70), pg.SRCALPHA)
    pg.draw.polygon(player_img, pg.Color('dodgerblue1'),
                    [(0, 70), (21, 2), (42, 70)])
    player_rect = player_img.get_rect(center=screen.get_rect().center)

    joysticks = [pg.joystick.Joystick(x) for x in range(pg.joystick.get_count())]
    for joystick in joysticks:
        joystick.init()

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        if len(joysticks) > 0:  # At least one joystick.
            # Use the stick axes to create a vector.
            vec = Vector2(joysticks[0].get_axis(0), joysticks[0].get_axis(1))
            radius, angle = vec.as_polar()  # angle is between -180 and 180.
            # Map the angle that as_polar returns to 0-360 with 0 pointing up.
            adjusted_angle = (angle+90) % 360
            pg.display.set_caption(
                'radius {:.2f} angle {:.2f} adjusted angle {:.2f}'.format(
                    radius, angle, adjusted_angle))

        # Rotate the image and get a new rect.
        player_rotated = pg.transform.rotozoom(player_img, -adjusted_angle, 1)
        player_rect = player_rotated.get_rect(center=player_rect.center)

        screen.fill((30, 30, 30))
        screen.blit(player_rotated, player_rect)
        pg.display.flip()
        clock.tick(60)


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