如何根据鼠标方向更改python中的精灵图像

时间:2013-09-04 17:15:57

标签: python sprite

我看过几篇关于更改精灵图片的帖子。 对于当前的赋值,我必须构造一个packman精灵,然后它应该跟随鼠标。没问题。 这是一段代码:

class Packman(games.Sprite):
    """Create the packman that is conrolled by the mouse"""
    #load the packman image
    image_right = games.load_image("snap_right.png") # initial value
    image_left = games.load_image("snap_left.png")
    show_image = image_right



    def __init__(self, x=games.mouse.x, y = games.mouse.y):
        """Initialise packman"""
        super(Packman, self).__init__(image = Packman.show_image, x = games.mouse.x, y = games.mouse.y)

    def update(self):
        """Move packmans coordinates"""
        self.x = games.mouse.x
        self.y = games.mouse.y

        if self.left < 0:
            self.left = 0

        if self.right > games.screen.width:
            self.right = games.screen.width

        #change Packman's direction that he is facing`

如您所见,我尝试加载两张图像,但一次只能显示一张图像。 (我认为有一种方法可以水平翻转一张图像,而不是使用两张图像。)按原样,我可以移动Packman。现在我需要根据鼠标的行进方向添加使Packman面向左/右的位。我的手册给了我一个示例,通过按键旋转图像180度,这可以工作,但然后packman只是倒置,他的眼睛在底部。

是否还有其他方法可以根据鼠标方向翻转打包器? (我只需要水平翻转,即左右)

1 个答案:

答案 0 :(得分:1)

我使用Pygame作为我的精灵,但解决方案非常简单。

我基本上使用这样的东西。指向初始化图像的两个指针。然后是指向image的指针的指针,这将是我们用来绘制精灵的指针。

# image is the pointer that points to the pointer that points to the image being currently used
image1 = pygame.image.load('left.png')
image2 = pygame.image.load('right.png')
image = image1

然后在画中我只是做

screen.blit(image, position)

现在,因为您正在使用鼠标来跟踪pacman的位置。你要做的就是这个。在EACH帧中,将鼠标x和y的位置存储在类变量中。称之为old_xold_y。在下一帧中,只需将鼠标x位置与old_x进行比较即可。如果鼠标位置较大,你的pacman正试图向右移动。 image = image2如果您的鼠标位置较小,那么您的pacman将向左移动。 image = image1应用必要的状态更改并相应地更改图像。