I'm trying to make multiple sprites that all come from the same pygame sprite class.
class animatedSprites(pygame.sprite.Sprite):
def __init__(self, spriteName):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width,height))
self.images = []
self.images.append(spriteName[0])
self.rect = self.image.get_rect() #sets sprites size and pos
self.rect.center = (POSITIONx1[4], POSITIONy1[4])
self.animation_frames = 12
self.current_frame = 0
self.previous_positiony = self.rect.y
self.previous_positionx = self.rect.x
def update(self):
global MOUSEPRESSED
if (MOUSEPRESSED == 1):
self.rect = self.image.get_rect()
self.rect.y = POSITIONy1[get_square_under_mousey()] - 25
self.rect.x = POSITIONx1[get_square_under_mousex()] - 25
if (MOUSEPRESSED == 2):
if collide(plant, bought2):
self.rect.y = self.previous_positiony
self.rect.x = self.previous_positionx
else:
self.rect = self.image.get_rect()
self.rect.y = POSITIONy1[get_square_under_mousey()] + 35#pulled x and y pos from func
self.rect.x = POSITIONx1[get_square_under_mousex()] - 25
self.previous_positiony = self.rect.y
self.previous_positionx = self.rect.x
MOUSEPRESSED = 0
I use this class to create a sprite on the screen, then use the def update() to control the sprite. The way the sprite is controlled is that when the user clicks on the sprite they can drag it around with their mouse and move it where ever they'd like on the screen. The problem is, if I use this class to create a second sprite and have two simultaneously on the screen, when the user "picks up" one sprite, they both move to the mouse position. I would like to make only one move depending on which is being clicked.
I'm assuming they're both moving to the same position because they both use the same def update() to decide their movement, so my question is, is there anyway in pygame or python to make the one being clicked on to move and not both, without creating a second
class animatedSprites(pygame.sprite.Sprite):
to make it. I would like to have multiple sprites on the screen at once but don't want to make dozens of individual classes and update() defs to control each one separately.
Sorry if this doesn't make sense, I'm a beginner to both python and pygame.
I recommend to create a class
DragOperator
which can drag anpygame.Rect
object:The dragging of the rectangle is implemented in the update method. Use this class in a
pygame.sprite.Sprite
object. Pass the list of events to theupdate
method of the Sprite and delegate it to the drag operator:Pass the list of event form the main application loop to the
pygame.sprite.Group
:Minmal example:
repl.it/@Rabbid76/PyGame-MouseDrag