Pygame / python鼠标按钮问题

时间:2012-06-22 00:50:24

标签: python mouseevent pygame mouseclick-event mouse-coordinates

我试图通过检查鼠标是否与对象rect碰撞并检查鼠标按钮是否已关闭来移动对象。

这是我的代码:

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

感谢您的帮助!

平安!

1 个答案:

答案 0 :(得分:2)

首次按下时,您将获得一个MOUSEBUTTONDOWN事件,但在按下该事件时不会。要确定用户何时停止按下它,您需要检查MOUSEBUTTONUP事件。

或者你可以使用pygame.mouse.get_pressed()来查询鼠​​标按钮的当前状态。鼠标功能文档为here