스프라이트를 클릭하는 마우스를 감지하는 코드를 작성하는 방법을 궁금합니다. 예 :파이 게임 마우스 클릭 감지
if #Function that checks for mouse clicked on Sprite:
print ("You have opened a chest!")
스프라이트를 클릭하는 마우스를 감지하는 코드를 작성하는 방법을 궁금합니다. 예 :파이 게임 마우스 클릭 감지
if #Function that checks for mouse clicked on Sprite:
print ("You have opened a chest!")
. pygame.mouse.get_pos
과 협력하여 pygame.mouse.get_pressed
방법을 사용할 수 있습니다 (필요한 경우). 그러나 메인 이벤트 루프를 통해 마우스 클릭 이벤트를 사용하십시오. 이벤트 루프가 더 좋은 이유는 "짧은 클릭"때문입니다. 일반 컴퓨터에서는이 사실을 알 수 없지만 트랙 패드에서 탭 클릭을 사용하는 컴퓨터의 클릭주기는 지나치게 짧습니다. 마우스 이벤트를 사용하면이 문제를 방지 할 수 있습니다.
편집 : 수행하기 위해 완벽한 픽셀 충돌 their docs for sprites에서 발견 pygame.sprite.collide_rect()
사용합니다.
게임에 주 루프가 있고 모든 스프라이트가 sprites
이라는 목록에 있다고 가정합니다.
메인 루프에서 모든 이벤트를 가져오고 MOUSEBUTTONDOWN
또는 MOUSEBUTTONUP
이벤트를 확인하십시오.
while ... # your main loop
# get all events
ev = pygame.event.get()
# proceed events
for event in ev:
# handle MOUSEBUTTONUP
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
# get a list of all sprites that are under the mouse cursor
clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
# do something with the clicked sprites...
그래서 기본적으로 메인 루프를 반복 할 때마다 스프라이트 클릭을 확인해야합니다. mouse.get_pos() 및 rect.collidepoint()을 사용하는 것이 좋습니다.
파이 게임은 이벤트 구동 프로그래밍을 제공하지 않습니다. cocos2d 않습니다.
또 다른 방법은 마우스 커서의 위치와 누른 단추의 상태를 확인하는 것이지만이 방법에는 몇 가지 문제가 있습니다.
if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()):
print ("You have opened a chest!")
당신은이 사건을 처리 그렇지 않으면이 코드는 인쇄하기 때문에, 플래그의 어떤 종류를 소개 할 것이다 "당신은 가슴을 열었습니다!" 메인 루프 반복마다.
handled = False
while ... // your loop
if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()) and not handled:
print ("You have opened a chest!")
handled = pygame.mouse.get_pressed()[0]
물론 당신은 Sprite
를 서브 클래스와 같은 is_clicked
라는 방법을 추가 할 수 있습니다
class MySprite(Sprite):
...
def is_clicked(self):
return pygame.mouse.get_pressed()[0] and self.rect.collidepoint(pygame.mouse.get_pos())
그래서, 첫 번째 방법 이럴을 사용하는 것이 좋습니다.
또한 마우스의 위치는 이벤트 자체에서'event.pos' 아래에 있습니다. –
나는이 질문에이를 긁적 많은 머리 후 같은 대답을 찾고 있었어요 내가 생각 해낸 대답은 :
#Python 3.4.3 with Pygame
import pygame
pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))
running = True
# Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
# Main Loop
while running:
# Mouse position and button clicking.
pos = pygame.mouse.get_pos()
pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
# Check if the rect collided with the mouse pos
# and if the left mouse button was pressed.
if Rectplace.collidepoint(pos) and pressed1:
print("You have opened a chest!")
# Quit pygame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
어떻게 적용 할 것이라고 생각 스프라이트 클릭에? –
@EliasBenevedes 픽셀 완전 충돌로 내 대답을 편집했습니다. – jakebird451