【问题标题】:how to continuesly move character when mousebutton is clicked单击鼠标按钮时如何连续移动字符
【发布时间】:2021-07-18 12:22:55
【问题描述】:

我想创建一个简单的程序,当您单击屏幕时,框会永远移动。看起来很简单,而且很可能是这样,但我似乎无法让它工作。

代码:

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),但这完全冻结了一切

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案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)
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-03-18
        • 2022-12-02
        • 1970-01-01
        • 2019-11-02
        • 2013-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多