单击鼠标按钮时如何继续移动字符

时间:2021-04-24 15:26:44

标签: python python-3.x pygame

我想创建一个简单的程序,当你点击屏幕时,盒子会永远移动。看起来很简单,而且可能很简单,但我似乎无法让它发挥作用。

代码:

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

没有错误,但我希望它连续平稳地移动而不停止。我怎样才能做到这一点?我试图放一个 for I in range(100) 但这只会使运动加倍,而且运动不顺畅。我也试过降低速度并放一个 pygame. time.sleep(100) 但这完全冻结了一切

2 个答案:

答案 0 :(得分:1)

您必须在事件循环中处理事件。单击鼠标并根据变量的状态移动对象时,设置一个布尔变量(move):

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)

答案 1 :(得分:1)

你可以在 if event.tpye == pygame.MOUSEBUTTONDOWN 中加入一个 if 语句,然后从那里移动

相关问题