[英]How do I respond to mouse clicks on sprites in PyGame?
在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())
關於它的一些問題:
提前致謝
我通常給我的可點擊對象一個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)
我想說這是推薦的做法。 點擊只注冊一次,所以如果用戶用一個按鈕“拖動”,它就不會告訴你的精靈。 使用MOUSEBUTTONDOWN事件設置為true的布爾值可以輕松完成,而使用MOUSEBUTTONUP設置為false。 為了激活它們的功能而迭代了“可拖動”對象......等等。
但是,如果您不想使用事件處理程序,可以讓更新函數檢查輸入:
pygame.mouse.get_pos()
pygame.mouse.get_pressed().
這對於較大的項目來說是一個壞主意,因為它可能很難找到錯誤。 更好地將事件保存在一個地方。 較小的游戲,如簡單的街機游戲,使用探測風格可能更有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.