-2
我想通過檢查鼠標是否與對象rect碰撞並檢查鼠標按鈕是否關閉來移動對象。pygame/python鼠標按鈕問題
這裏是我的代碼:
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()
這工作,但我有垃圾郵件對我的鼠標每個按鈕並最終pygame的會拿起鼠標事件和期望的對象會移動,但只有一秒鐘那麼它會停止。
我的目標是點擊鼠標上的一個按鈕,如果鼠標與盒子碰撞,那麼盒子將移動,而鼠標按鈕向下移動到鼠標x和y。
我希望我清楚。
感謝您的任何幫助
和平!
這是我如何得到它的工作:
#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
感謝您的幫助!
平安!
謝謝,你的回答對我有很大的幫助,現在我已經按預期工作。我會將我的代碼張貼給其他人看作爲示例。 – user1473612