简体   繁体   English

如何在PyGame中响应鼠标点击sprite?

[英]How do I respond to mouse clicks on sprites in PyGame?

What is the canonical way of making your sprites respond to mouse clicks in PyGame ? 在PyGame中让精灵响应鼠标点击的规范方法是什么?

Here's something simple, in my event loop: 在我的事件循环中,这里有一些简单的东西:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        exit_game()
    [...]
    elif (  event.type == pygame.MOUSEBUTTONDOWN and
            pygame.mouse.get_pressed()[0]):
        for sprite in sprites:
            sprite.mouse_click(pygame.mouse.get_pos())

Some questions about it: 关于它的一些问题:

  1. Is this the best way of responding to mouse clicks ? 这是响应鼠标点击的最佳方式吗?
  2. What if the mouse stays pressed on the sprite for some time ? 如果鼠标在精灵上按下一段时间怎么办? How do I make a single event out of it ? 如何从中制作单个活动?
  3. Is this a reasonable way to notify all my sprites of the click ? 这是通知我所有精灵点击的合理方式吗?

Thanks in advance 提前致谢

I usually give my clickable objects a click function, like in your example. 我通常给我的可点击对象一个click功能,就像你的例子一样。 I put all of those objects in a list, for easy iteration when the click functions are to be called. 我将所有这些对象放在一个列表中,以便在调用click函数时轻松迭代。

when checking for which mousebutton you press, use the button property of the event. 在检查您按哪个鼠标按钮时,请使用事件的按钮属性。

import pygame
from pygame.locals import * #This lets you use pygame's constants directly.

for event in pygame.event.get():
    if event.type == MOUSEBUTTONDOWN:  #Better to seperate to a new if statement aswell, since there's more buttons that can be clicked and makes for cleaner code.
        if event.button == 1:
            for object in clickableObjectsList:
                object.clickCheck(event.pos)

I would say this is the recommended way of doing it. 我想说这是推荐的做法。 The click only registers once, so it wont tell your sprite if the user is "dragging" with a button. 点击只注册一次,所以如果用户用一个按钮“拖动”,它就不会告诉你的精灵。 That can easily be done with a boolean that is set to true with the MOUSEBUTTONDOWN event, and false with the MOUSEBUTTONUP. 使用MOUSEBUTTONDOWN事件设置为true的布尔值可以轻松完成,而使用MOUSEBUTTONUP设置为false。 The have "draggable" objects iterated for activating their functions... and so on. 为了激活它们的功能而迭代了“可拖动”对象......等等。

However, if you don't want to use an event handler, you can let an update function check for input with: 但是,如果您不想使用事件处理程序,可以让更新函数检查输入:

pygame.mouse.get_pos() 
pygame.mouse.get_pressed().

This is a bad idea for larger projects, since it can create hard to find bugs. 这对于较大的项目来说是一个坏主意,因为它可能很难找到错误。 Better just keeping events in one place. 更好地将事件保存在一个地方。 Smaller games, like simple arcade games might make more sense using the probing style though. 较小的游戏,如简单的街机游戏,使用探测风格可能更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM