繁体   English   中英

pygame检测鼠标光标在对象上

[英]pygame detecting mouse cursor over object

我想在鼠标光标悬停在我加载到屏幕上的图像上方时打印一条语句,但是仅当鼠标光标悬停在屏幕的左上方时才打印语句,即使该图像位于中间或右下角。

import pygame, sys
from pygame import *

def main():
    pygame.init()
    FPS = 30
    fpsClock = pygame.time.Clock()
    screen = pygame.display.set_mode((600, 400))
    cat = pygame.image.load('cat.png')

    while True:
        if cat.get_rect().collidepoint(pygame.mouse.get_pos()):
            print "The mouse cursor is hovering over the cat"

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        screen.blit(cat, (300, 100))
        pygame.display.flip()
        fpsClock.tick(FPS)
main()

Surface.get_rect()方法返回一个矩形,该矩形与图像大小相同,但位置不同! 您将获得一个位于(0,0)的矩形,这就是为什么当鼠标位于左上角时会打印出来的原因。 相反,您可以做的是获取用于Surface.get_rect(x=300, y=100)曲面的参数,并将其传递给Surface.get_rect(x=300, y=100)

甚至更好的是,在加载图像的同时创建矩形。 这样,您不必在每个循环中都创建一个新的矩形。 然后,您可以根据矩形定位图像:

import pygame, sys
from pygame import *

def main():
    pygame.init()
    FPS = 30
    fpsClock = pygame.time.Clock()
    screen = pygame.display.set_mode((600, 400))
    cat = pygame.image.load('cat.png')
    rect = cat.get_rect(x=300, y=100)  # Create rectangle the same size as 'cat.png'.

    while True:
        if rect.collidepoint(pygame.mouse.get_pos()):
            print "The mouse cursor is hovering over the cat"

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        screen.blit(cat, rect)  # Use your rect to position the cat.
        pygame.display.flip()
        fpsClock.tick(FPS)
main()

暂无
暂无

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

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