问题描述
我遇到了一个问题,当我点击按钮时我有一个按钮我增加了我的健康矩形宽度 + 1 问题是当我用鼠标按住按钮时我希望健康矩形保持即使我在窗口周围移动鼠标,也会增加它的宽度,但是一旦我在窗口周围移动鼠标,健康矩形就会停止添加
VIDEO 我做到了,所以如果我停止按住鼠标应该停止添加它,但它会检测到我何时移动鼠标以及如何解决这个问题
在我的主循环中,我说如果我的鼠标在速度按钮上,那么它会继续添加,否则当我不再点击按钮时它应该停止添加但是当我移动鼠标时它也会停止添加我的健康
># our main loop
ble = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
if speedbutton.isOver(pos):
ble = True
else:
#[...]
ble = False
# if my ble is True then I will keep adding the health bar
if ble:
if health1.health < 70:
health1.health += 0.4
解决方法
当鼠标未在按钮上或松开按钮时,您必须重置 ble
(MOUSEBUTTONUP
- 参见 pygame.event
):
ble = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if speedbutton.isOver(event.pos):
ble = True
elif event.type == pygame.MOUSEBUTTONUP:
ble = False
# if my ble is True then I will keep adding the health bar
if not speedbutton.isOver(pygame.mouse.get_pos()):
ble = False
if ble:
if health1.health < 70:
health1.health += 0.4
或者,您可以使用 pygame.mouse.get_pressed()
。 pygame.mouse.get_pressed()
返回一个布尔值列表,代表所有鼠标按钮的状态(True
或 False
)。只要按钮被按住,按钮的状态就是 True
。
使用 any
评估是否按下了任何鼠标按钮:
ble = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
mouse_buttons = pygame.mouse.get_pressed()
pos = pygame.mouse.get_pos()
ble = any(mouse_buttons) and speedbutton.isOver(pos)
# if my ble is True then I will keep adding the health bar
if ble:
if health1.health < 70:
health1.health += 0.4