pygame:图像和精灵有什么区别? [英] pygame: What is the difference between an image and a sprite?

查看:90
本文介绍了pygame:图像和精灵有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

导入火箭精灵(例如)并将其设置为图像与导入火箭精灵并将其设置为 pygame 中的精灵有什么区别?

What is the difference between importing a rocket sprite (for example) and setting it as an image vs importing a rocket sprite and setting it as a sprite in pygame?

推荐答案

我认为您只是对术语感到困惑:

I think you're just getting confused about the terminology:

  • 图片

图像只是像素的集合.您正在使用精灵"来引用磁盘上的图像,但这只是一个图像文件.要使用您的火箭示例,您可以像这样加载图像:

An image is just a collection of pixels. You're using "sprite" to refer to an image on the disk, but that's just an image file. To use your rocket example, you would load the image like this:

rocket_img = pygame.image.load('rocket.png').convert_alpha()

然后你可以在任何你想要的地方绘制这个图像:

You can then draw this image anywhere you want with:

screen.blit(rocket_img, (x, y))

  • 精灵
  • Pygame 中的精灵是一个对象,具有完整的内置功能集合.精灵 将图像作为其属性之一,但还有更多.此外,您可以将精灵组合在一起,使它们更容易更新或绘制.精灵具有内置的碰撞功能.您可以添加自己的属性来跟踪位置、速度、动画等.

    A sprite in Pygame is an object, with a whole collection of built-in functionality. Sprites have an image as one of their properties, but there are a whole lot more. Plus you can put sprites together in groups to make them easier to update or draw. Sprites have collision functionality built into them. You can add your own properties to track location, velocity, animation, etc.

    一个简单的精灵:

    class Rocket(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
            self.image = pygame.image.load('rocket.png').convert_alpha()
            self.rect = self.image.get_rect()
    
        def update(self):
            self.rect.x += 1
    

    这将是一个火箭精灵,您可以使用它来实例化

    This would be a rocket sprite that you would instantiate by using

    rocket = Rocket()
    

    您可以使用绘图

    screen.blit(rocket.image, rocket.rect)
    

    它慢慢向右移动(如果你在游戏循环中调用 update() :

    and it moves slowly to the right (if you call update() in the game loop:

    rocket.update()
    

    我建议您查看 Sprite 文档 - 您可以通过群组执行更多操作,从而使处理大量 Sprite 变得非常容易.

    I recommend looking at the Sprite docs - there's lots more you can do with groups to make working with lots of sprites very easy.

    http://www.pygame.org/docs/ref/sprite.html

    这篇关于pygame:图像和精灵有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆