-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() 

이 작동하지만 내 마우스의 모든 버튼을 스팸해야하고 결국 파이 게임은 마우스 이벤트를 선택하고 의도 한대로 개체 만 분할에 대한 이동합니다 초 그 때 그것은 멈출 것이다.

내 목표는 마우스의 버튼을 클릭하기 만하면 마우스가 상자와 충돌하는 경우 마우스 버튼이 마우스 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 

감사합니다!

평화!

답변

2

처음 눌렀을 때 MOUSEBUTTONDOWN 이벤트가 발생하지만, 눌려 졌을 때 MOUSEBUTTONDOWN 이벤트는 발생하지 않습니다. 사용자가 누를 때를 판별하려면 MOUSEBUTTONUP 이벤트를 점검해야합니다.

또는 pygame.mouse.get_pressed()를 사용하여 마우스 버튼의 현재 상태를 확인할 수 있습니다. 마우스 기능 문서는 here입니다.

+0

감사합니다. 귀하의 답변이 많은 도움이되었습니다. 이제는 의도 한대로 작동하게되었습니다. 다른 사람들이 예제로보기 위해 제 코드를 게시 할 것입니다. – user1473612

관련 문제