我试图移动一个对象,通过检查鼠标是否与对象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
谢谢你的帮助!
和平!
当第一次按下鼠标按钮时,您将得到一个MOUSEBUTTONDOWN事件,但当它被按住时,您不会得到它。要确定用户何时停止按下鼠标,需要检查MOUSEBUTTONUP事件。
或者可以使用pygame.mouse.get_pressed()来查询鼠标按钮的当前状态。鼠标功能文档是here。
相关问题 更多 >
编程相关推荐