pygame检测鼠标光标在对象上 [英] pygame detecting mouse cursor over object

查看:72
本文介绍了pygame检测鼠标光标在对象上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在鼠标光标悬停在我加载到屏幕上的图像上时打印一条语句,但它仅在鼠标光标悬停在屏幕左上角时打印,即使图像位于中心或底部没错.

I want to print a statement when the mouse cursor hovers over an image I loaded onto the screen, but it only prints when the mouse cursor hovers over the top left portion of the screen even if the image is in the center or bottom right.

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).

The method Surface.get_rect() returns a rectangle of the same size as the image but not at the same position! You'll get a rectangle positioned at (0, 0) which is why it prints when your mouse is in the top left corner. What you can do instead is take the arguments you use to position the surface and pass them to the method Surface.get_rect(x=300, y=100).

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

Or even better, create the rectangle at the same time you load your image. That way you don't have to create a new rectangle every loop. You could then position your image based on the rect:

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()

这篇关于pygame检测鼠标光标在对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆