how to continuesly move character when mousebutton is clicked

Viewed 42

I want to create a simple program that when you click on the screen, the box moves forever. It seems very simple, and it probably is, but I can't seem to make it work.

code:

import pygame
import sys
from pygame.locals import *

count = 0

def blast1():
    global bl, blast
    blast.y = bl
    # ran = random.randint(0, 450)

pygame.init()
running = True

clock = pygame.time.Clock()
bl = 10

blast = pygame.Rect(300, 200 ,20,20)
screen = pygame.display.set_mode((500, 500))


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

    blast1()

    screen.fill((255, 255, 255)) #color

    pygame.draw.ellipse(screen, [0, 255, 0], blast)
    
    keys=pygame.key.get_pressed()

    if event.type == pygame.MOUSEBUTTONDOWN and count != 1:
        blast.x += bl
        count = 1

        

    
    pygame.display.flip()
    
    clock.tick(30)
pygame.quit()

There are no errors but I want it to move continuously and smoothly without stopping. How can I do this? I have tried to put a for I in range(100) but that only doubles the movement and it doesn't move smoothly. I have also tried to lower the speed and put a pygame. time.sleep(100) but that completely freezes everything

2 Answers

You must handle the event in the event loop. Set a Boolean variable (move) when you click the mouse and move the object depending on the state of the variable:

moving = False
count = 0

blast1()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN1:
            moving = True

    if moving and count < 100:
        blast.x += 1
        count += 1  
    
    screen.fill((255, 255, 255)) #color
    pygame.draw.ellipse(screen, [0, 255, 0], blast)
    pygame.display.flip()
    
    clock.tick(30)

you could just put in the if event.tpye == pygame.MOUSEBUTTONDOWN an if statment with the cound and then move from there

Related