Mar*_*nen 1 python pygame sprite python-3.x
我已经找到了很多关于如何以及何时使用精灵的教程,但我仍然不知道它们是什么或它们做什么。默认的想法似乎是您对pygame.sprite.Sprite类进行子类化并向类添加rect和image属性。但是为什么我需要对类进行子Sprite类化,它如何影响我的代码?反正我可以这样做:
class MySprite: # No subclassing!
def __init__(self, image):
self.image = image
self.rect = image.get_rect()
Run Code Online (Sandbox Code Playgroud)
它似乎工作得很好。我也尝试过查看源代码,但找不到精灵文件。
精灵只是游戏中的对象,可以与其他精灵或其他任何东西进行交互。这些可以包括角色、建筑物或其他游戏对象。
Sprites 有一个子类的原因更多是为了方便。当一个对象从sprite.Sprite类继承时,它们可以被添加到一个精灵组中。
例子:
import pygame
class car(sprite.Sprite):
def __init__(self):
sprite.Sprite.__init__() # necessary to initialize Sprite class
self.image = image # insert image
self.rect = self.image.get_rect() #define rect
self.rect.x = 0 # set up sprite location
self.rect.y = 0 # set up sprite location
def update(self):
pass # put code in here
cars = pygame.sprite.Group()# define a group
pygame.sprite.Group.add(car())# add an instance of car to group
Run Code Online (Sandbox Code Playgroud)
我不能将精灵添加到精灵组,除非它们继承自精灵类。这很有用,因为我现在可以做一些事情,比如更新组中的所有精灵并用一个函数绘制它们:
cars.update() #calls the update function on all sprites in group
cars.draw(surface) #draws all sprites in the group
Run Code Online (Sandbox Code Playgroud)
我还可以使用组进行碰撞检测:
# check to see if sprite collides with any sprite in the car group
collided = pygame.sprite.Sprite.spritecollide(sprite, cars, False)
Run Code Online (Sandbox Code Playgroud)
注意:在上面的代码中
pygame.sprite.Sprite.spritecollide返回一个列表。
总之,精灵类对于处理大量精灵很有用,否则这些精灵将需要更多的代码来管理。本Sprite类提供了一套通用的,可用于定义精灵变量。
| 归档时间: |
|
| 查看次数: |
1451 次 |
| 最近记录: |