首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >玩偶游戏检测物体上的鼠标光标

玩偶游戏检测物体上的鼠标光标
EN

Stack Overflow用户
提问于 2016-12-09 16:01:37
回答 1查看 1.6K关注 0票数 1

当鼠标光标悬停在我加载到屏幕上的图像时,我想打印一条语句,但只有当鼠标光标悬停在屏幕的左上部分时,即使图像位于右下角或中间位置,它才会打印出来。

代码语言:javascript
运行
复制
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()
EN

Stack Overflow用户

回答已采纳

发布于 2016-12-09 16:36:26

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

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

代码语言:javascript
运行
复制
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()
票数 3
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41064365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档