-2

我试图通过检查鼠标是否与对象 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

谢谢您的帮助!

和平!

4

1 回答 1

2

当它第一次被按下时你会得到一个 MOUSEBUTTONDOWN 事件,但当它被按下时不会。要确定用户何时停止按下它,您需要检查 MOUSEBUTTONUP 事件。

或者,您可以使用 pygame.mouse.get_pressed() 来查询鼠标按钮的当前状态。鼠标功能文档在这里

于 2012-06-22T00:59:19.280 回答