gpt4 book ai didi

python - Pygame - 在两点之间移动矩形

转载 作者:行者123 更新时间:2023-12-01 09:05:44 28 4
gpt4 key购买 nike

我正在尝试在 pygame 中的两点之间进行直线移动。我已经能够让它移动到另一个矩形上然后停止,但它不会像它应该的那样向后移动。我不确定我做错了什么,所以我决定寻求帮助。这是我的代码:

import pygame

width, height = 800, 600
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Test")
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10


def gameloop():
lead_x1, lead_x2 = 1, 100
lead_y1, lead_y2 = 1, 1
velocity = 0.2
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10

while not gameExit:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [lead_x1, lead_y1, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x2, lead_y2, block_size, block_size])
lead_x1 += velocity
if lead_x1 >= lead_x2:
lead_x1 += -velocity
if lead_x1 <= 0:
lead_x1 += velocity
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.display.update()
pygame.quit()
quit()
gameloop()

最佳答案

我认为你需要放置行 lead_x1 += velocity在 else 语句中,如下所示:-

import pygame

width, height = 800, 600
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Test")
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10


def gameloop():
lead_x1, lead_x2 = 1, 100
lead_y1, lead_y2 = 1, 1
velocity = 0.2
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
toogle_flag = 1
while not gameExit:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [lead_x1, lead_y1, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x2, lead_y2, block_size, block_size])
lead_x1 += toggle_flag * velocity
if lead_x1 >= lead_x2:
toggle_flag = -1*toggle_flag
if lead_x1 <= 0:
toggle_flag = -1*toggle_flag
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.display.update()
pygame.quit()
quit()
gameloop()

所以我在这里要做的是,让我们采用一个名为 toggle_flag 的标志。 ,将其初始化为1 .

  1. 发件箱位于位置 1,我们添加 toggle_flag * velocity到我们的lead_x1 。即我们基本上添加 velocity .

  2. 一旦我们触摸第二个框,我们就会翻转 toggle_flag 的值。至-1 。将会发生的是,我们继续添加 -velocity到我们的lead_x1 .

  3. 现在,一旦我们到达 0 。我们再次翻转 toggle_flag 的值乘以 -1 ,我们让我们添加 velocitylead_x1

希望这有帮助!

关于python - Pygame - 在两点之间移动矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52070631/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com