如何使矩形“冲刺”

import pygame


width = 500

height = 500

win = pygame.display.set_mode((width, height))

pygame.display.set_caption("Client")

running = False


clientNumber = 0


class Player():

    def __init__(self, x, y, width, height, color):

        self.x = x

        self.y = y

        self.width = width

        self.height = height

        self.color = color

        self.rect = (x, y, width, height)

        self.vel = 3


    def draw(self, win):

        pygame.draw.rect(win, self.color, self.rect)


    def move(self):

        keys = pygame.key.get_pressed()

        running = bool


        if keys[pygame.K_LEFT]:

            self.x -= self.vel


        if keys[pygame.K_RIGHT]:

            self.x += self.vel


        if keys[pygame.K_UP]:

            self.y -= self.vel


        if keys[pygame.K_DOWN]:

            self.y += self.vel


        if keys[pygame.K_a] and not running:

            self.vel += 3

            running = True


        if not keys[pygame.K_a]:

            running = False



        self.rect = (self.x, self.y, self.width, self.height)




def redrawWindow(win, player):


    win.fill((255, 255, 255))

    player.draw(win)

    pygame.display.update()



def main():

    run = True

    p = Player(50, 50, 100, 100, (0, 0, 255))

    clock = pygame.time.Clock()


    while run:

        clock.tick(60)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                run = False

                pygame.quit()


        p.move()

        redrawWindow(win, p)


main()

我成功地制作了一个可以通过键盘输入移动的矩形物体。现在我想改变矩形的速度,就像按“a”时,速度从 3 更改为 6。但我不知道该怎么做。我尝试创建一个“正在运行”的布尔变量,以仅在您按下它时而不是按下它时加速它。但我所有的努力都失败了。


慕工程0101907
浏览 104回答 1
1回答

慕神8447489

current_vel计算取决于 的关键状态的当前速度 ( ) a。用于current_vel移动玩家而不是self.vel:class Player():    # [...]    def move(self):        keys = pygame.key.get_pressed()        current_vel = self.vel        if keys[pygame.K_a]:            current_vel += 3        if keys[pygame.K_LEFT]:            self.x -= current_vel         if keys[pygame.K_RIGHT]:            self.x += current_vel         if keys[pygame.K_UP]:            self.y -= current_vel         if keys[pygame.K_DOWN]:            self.y += current_vel         self.rect = (self.x, self.y, self.width, self.height)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python