I am trying to move an object by checking if the mouse is colliding with the objects rect and checking if a mouse button is down.
here is my code:
class Unit(pygame.sprite.Sprite):
def __init__(self, display,):
pygame.sprite.Sprite.__init__(self,)
self.master_image = pygame.Surface((50, 100))
self.master_image.fill((000,255,000))
self.image = self.master_image
self.rect = self.image.get_rect()
self.rect.centerx = 500
self.rect.centery = 500
def move(self):
mouse = pygame.Surface((5, 5))
mouse_rect = mouse.get_rect()
(mouseX, mouseY) = pygame.mouse.get_pos()
mouse_rect.centerx = mouseX
mouse_rect.centery = mouseY
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if mouse_rect.colliderect(self.rect):
self.rect.centerx = mouseX
self.rect.centery = mouseY
print "move"
def update(self,):
self.move()
This works but I have to spam every button on my mouse and eventually pygame will pick up the mouse event and the object will move as intended but only for a split second then it will stop.
My goal is just to click a button on the mouse and if the mouse is colliding with the box then the box will move whilst the mouse button is down to the mouse x and y.
I hope I am being clear.
Thanks for any help
peace!
Here is how I got it to work:
#unit sprite class
class Unit(pygame.sprite.Sprite):
def __init__(self, display,):
pygame.sprite.Sprite.__init__(self,)
self.master_image = pygame.Surface((50, 100))
self.master_image.fill((000,255,000))
self.image = self.master_image
self.rect = self.image.get_rect()
self.rect.centerx = 500
self.rect.centery = 500
#mouse stuff
self.mouse = pygame.Surface((5, 5))
self.mouse_rect = self.mouse.get_rect()
(self.mouse_rect.centerx , self.mouse_rect.centery) = pygame.mouse.get_pos()
def move(self):
if pygame.MOUSEBUTTONDOWN:#check for mouse button down
(button1, button2, button3,) = pygame.mouse.get_pressed()#get button pressed
if button1 and self.mouse_rect.colliderect(self.rect):#check for collision between object and mouse
(self.rect.centerx, self.rect.centery) = pygame.mouse.get_pos()#set object POS to mouse POS
def update(self,):
(self.mouse_rect.centerx , self.mouse_rect.centery) = pygame.mouse.get_pos()#update mouse RECT
self.move()#check movement
thanks for the help!
peace!