在PyGame中让精灵响应鼠标点击的规范方法是什么?
在我的事件循环中,这里有一些简单的东西:
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())
Run Code Online (Sandbox Code Playgroud)
关于它的一些问题:
提前致谢
Zoo*_*tor 10
我通常给我的可点击对象一个click功能,就像你的例子一样.我将所有这些对象放在一个列表中,以便在调用click函数时轻松迭代.
在检查您按哪个鼠标按钮时,请使用事件的按钮属性.
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)
Run Code Online (Sandbox Code Playgroud)
我想说这是推荐的做法.点击只注册一次,所以如果用户用一个按钮"拖动",它就不会告诉你的精灵.使用MOUSEBUTTONDOWN事件设置为true的布尔值可以轻松完成,而使用MOUSEBUTTONUP设置为false.为了激活它们的功能而迭代了"可拖动"对象......等等.
但是,如果您不想使用事件处理程序,可以让更新函数检查输入:
pygame.mouse.get_pos()
pygame.mouse.get_pressed().
Run Code Online (Sandbox Code Playgroud)
这对于较大的项目来说是一个坏主意,因为它可能很难找到错误.更好地将事件保存在一个地方.较小的游戏,如简单的街机游戏,使用探测风格可能更有意义.
| 归档时间: |
|
| 查看次数: |
10698 次 |
| 最近记录: |