Mouse placement in the center of a rectangle with pygame.mouse.get_pos()

Asked

Viewed 28 times

0

Hello!

I read the following code with Pygame:

import pygame

PRETO = (0,0,0)
AMARELO = (255,255,0)
VERMELHO = (255,0,0)
VERDE = (0,255,0)
AZUL = (0,0,255)
BRANCO = (255,255,255)

LARGURAJANELA = 500
ALTURAJANELA = 400

pygame.init()

janela = pygame.display.set_mode((LARGURAJANELA, ALTURAJANELA))
label = pygame.display.set_caption("Retang acompanha o mouse com delay_CLOCK")
relogio = pygame.time.Clock()

ret = pygame.Rect(10, 10, 100, 50)

cont = True

while cont:
    relogio.tick(20) # Altere o valor para alterar o delay
    pygame.display.update()
    janela.fill((PRETO))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            cont = False

    (ret.left, ret.top) = pygame.mouse.get_pos()
    ret.left -= ret.width/2
    ret.top -= ret.height/2

    janela.fill(AMARELO)
    pygame.draw.rect(janela, AZUL, ret)
    pygame.display.update()

pygame.quit()

I did not understand this stretch to center the mouse pointer in the rectangle when there is movement:

(ret.left, ret.top) = pygame.mouse.get_pos()
ret.left -= ret.width/2
ret.top -= ret.height/2

When it was just, (ret.left, ret.top) = pygame.mouse.get_pos(), ok. The position of the mouse pointer is equal to the left and top position of the rectangle.

But, when you decrement Ret.left and Ret.top, why does the mouse stay in the center? The value of Ret.left, for example, would not be its current value less than half the width?

In fact, I don’t understand. If anyone can explain it to me I appreciate it. I’ve already searched the web and found nothing.

Thank you

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.