简体   繁体   English

单击矩形时连续移动矩形(pygame)

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

I already made that if I click on the rectangle it moves on X axis by +1.我已经做到了,如果我单击矩形,它会在 X 轴上移动 +1。 But I want the movement to be endless so that it would go off the screen.但我希望运动是无穷无尽的,这样它就会 go 离开屏幕。 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()

Correct the Indentation .更正缩进 The MOUSEBUTTONDOWN event must be evaluated in the event loop, instead of the application loop. MOUSEBUTTONDOWN事件必须在事件循环中计算,而不是在应用程序循环中计算。

Set a state variable ( move ) when the mouse button is clicked and move the object depending on the state of the variable:单击鼠标按钮时设置一个 state 变量( move ),并根据变量的 state 移动 object:

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)
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM