[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Another sprite issue.



They are all using the same rect object, and you are positioning that 1 single rect to the location of the wall. So collision is working for all, but all of them are positioned in the same place.

Instead of calling get_rect once and reusing the result, you should pass the image to each sprite and have them each call get_rect themselves to get their own unique rect.


On Mon, Jul 28, 2008 at 8:36 PM, <percivalkelley@xxxxxxxxx> wrote:
I want to display sprites with the same graphic across several areas
of my game. So I load the image into one variable, and then create all
my sprites from that same image.

All the sprites appear properly, but collision detection only works on
the last sprite drawn using the variable with the image. Why is this?
Do I have to reload the image everytime?

This is my code to load the image:

def load_image(name, transparent=0, colorkey=None): #from the line-by-
line chimp tutorial
   fullname = os.path.join('img', name)
   try:
               if transparent == 0:
                       image = pygame.image.load(fullname).convert()
               else:
                       image = pygame.image.load(fullname).convert_alpha()
   except pygame.error, message:
       print 'Cannot load image:', name
       raise SystemExit, message
   if colorkey is not None:
       if colorkey is -1:
           colorkey = image.get_at((0,0))
       image.set_colorkey(colorkey, RLEACCEL)
   return image, image.get_rect()

To setup the sprite:

class Units(pygame.sprite.Sprite):

       def __init__(self, img, loc1 = 250, loc2 = 250):
               pygame.sprite.Sprite.__init__(self) #start up sprites

               #locs
               self.loc1 = loc1
               self.loc2 = loc2

               #create sprite
               self.image, self.rect = img
               self.rect.center = [self.loc1, self.loc2]

and actually making the sprites:

wallGfx = load_image('wall.png', 1)
self.wall1 = Units(wallGfx2, 400, 325)
self.screen.blit(self.wall1.image, self.wall1.rect)

self.wall2 = Units(wallGfx, 400, 400)
self.screen.blit(self.wall2.image, self.wall2.rect)
self.egroup = pygame.sprite.RenderUpdates(self.wall1, self.wall2)

pygame.display.update()

Now, doing this, only the sprite at 400,400 (self.wall2) will have
proper collision detection. They're both displayed, but only the last
one added to the group has it. If I remove self.wall2, self.wall1 will
detect it properly.

Any ideas?

Thanks in advance.