[Python] Posicionamento do mouse no centro de um retângulo com pygame.mouse.get_pos()

Discussão em 'Python' iniciado por Stack, Outubro 20, 2024.

  1. Stack

    Stack Membro Participativo

    Olá!

    Li o seguinte código com 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()


    Eu não entendi esse trecho para centralizar o ponteiro do mouse no retângulo quando há movimento:

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


    Quando era, apenas, (ret.left, ret.top) = pygame.mouse.get_pos(), ok. A posição do ponteiro o mouse é igual a posição left e top do retângulo.

    Mas, quando você decrementa o ret.left e o ret.top, por que o mouse fica no centro? O valor de ret.left, por exemplo, não seria o valor atual dele menos a metade da largura?

    De fato, eu não entendi. Se alguém puder me explicar eu agradeço. Já pesquisei na web e não achei nada.

    Obrigado

    Continue reading...

Compartilhe esta Página