简体   繁体   中英

pygame detecting mouse cursor over object

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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