Continuous movement for a rectangle when I click on it (pygame)

Viewed 55

I already made that if I click on the rectangle it moves on X axis by +1. But I want the movement to be endless so that it would go off the screen. Well the main goal is that when I would click on the rectangle it would move from left to right until it gets another click and then it stops.

import pygame
from pygame.constants import MOUSEBUTTONDOWN

pygame.init()

#variables
W, H =500, 500
screen=pygame.display.set_mode((W, H))
surf = pygame.Surface((50,50))
surf.fill('white')
kubiks = surf.get_rect(topleft= (0,0))
fps=60
clock=pygame.time.Clock()

#display shit
def game_display(kubiks):
    screen.fill('Red')
    screen.blit(surf, (kubiks.x, kubiks.y))    
    pygame.display.update()

#Cube movement
def cube_movment(kubiks):
    kubiks.x +=1

run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            break
    if event.type == pygame.MOUSEBUTTONDOWN:
        x, y = event.pos
        if kubiks.collidepoint(x, y):
            cube_movment(kubiks)
                
    game_display(kubiks)

pygame.quit()
2 Answers

Correct the Indentation. The MOUSEBUTTONDOWN event must be evaluated in the event loop, instead of the application loop.

Set a state variable (move) when the mouse button is clicked and move the object depending on the state of the variable:

move = False

run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            break

    # INDENTATION
    #-->|
        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            if kubiks.collidepoint(x, y):
                move = not move
   
    if move:
        cube_movment(kubiks)
             
    game_display(kubiks)

pygame.quit()

You can do that in few lines of code:

continuous_mov = False
while run:
    mouse = pygame.mouse.get_pos()
    if kubikx.collidepoint(mouse) and pygame.mouse.get_pressed()[0]:
        contiuous_mov = not continuous_mov
    if continuous_mov:
        cube_movement(kubikx)
    
Related