Reputation: 113
TL;DR: How to get an attribute of an object that is in a sprite group
I have a sprite group called 'all_bullets'. I am trying to make a boomerang-engine, so when I shoot (press space) a bullet object will be added to the all_bullets group (I have the class coded already). But, I don't want to be able to shoot as many boomerangs as I can. So, I only want to create a bullet object when there is no boomerang (bullet object) in the sprite group, so I know there is no boomerang in the screen. But there are also other bullets. Like a pistol. So I want to know how to get the .image attribute of an object that is inside a sprite group; there are multiple objects in that group so just typing 'bullet.image' wont work I tried it. Any suggestions? Thanks in advance
Upvotes: 1
Views: 1322
Reputation: 14916
It's hard to answer without any code. But what you suggest, directly referencing the sprite's .image
directly should work.
Consider a simple Bullet
sprite:
class BulletSprite( pygame.sprite.Sprite ):
def __init__( self, filename, from_point, to_point, speed=1 ):
pygame.sprite.Sprite.__init__( self )
self.image = pygame.image.load( filename ).convert_alpha()
self.rect = self.image.get_rect()
self.speed = speed
self.rect.center = ( from_point )
self.x = from_point[0]
self.y = from_point[1]
#...
With a sprite group:
all_bullets = pygame.sprite.Group()
# Add some bullets
for i in range( 5 ):
from_point = ( 0, WINDOW_HEIGHT//2 ) # middle left
to_point = ( WINDOW_WIDTH, 100 * i ) # somewhere right
# create the bullet
new_bullet = Bullet( 'bullet.png', from_point, to_point )
all_bullets.add( to_point )
# and one more:
boomerang1 = Bullet( 'boomerang.png', ( 0, 0 ), ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
all_bullets.add( boomerang1 )
Now it's absolutely possible to iterate over this list using/accessing the individual sprite's .image
members:
for bullet in all_bullets: # every sprite in the group
window.blit( bullet.image, ( bullet.x, bullet.y ) ) # paint the image
Note this is probably not the best way of doing this, as an objects internal parts are best left to the object to use itself. So in the above case, you would create a bullet.draw()
function, and call it to draw the image
.
Upvotes: 2