gpt4 book ai didi

python - Pygame - 运动加速

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

我想用python/pygame制作一个脚本,当你按住移动按钮时,角色会加速(所以,当我按住左键时,角色会加速到特定的速度,然后速度会均匀)出来,当我松开按键时,它的速度会慢慢降低,直到完全停止。)

目前,我的代码将识别出角色必须加速,但是速度的变化仅在每次按下并释放按键时发生(例如:第一次按键速度为 1,第二次按键速度为 1)为两次,一直到第五次或第六次按下时处于最大速度,然后重置。)

我想编写我的代码,这样这意味着角色将在按住按键时加速,而不需要多次按下。

这是到目前为止我的代码的移动部分(周围还有一些随机位):

x = (display_width * 0.45)
y = display_height * 0.8
x_change = 0
negx = 0
posx = 0
bun_speed = 0

while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
posx = 0
if negx != -5:
negx = negx - 1
x_change = negx
elif negx == -5:
negx = 0
x_change = -5
elif event.key == pygame.K_RIGHT:
negx = 0
if posx != 5:
posx = posx + 1
x_change = posx
elif posx == 5:
posx = 0
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
elif event.key == pygame.K_RIGHT:
x_change = 0
x += x_change

display.fill(white)
bunny(x,y)

pygame.display.update()
clock.tick(60)

两个变量 negx 和 posx 分别根据按下的键而减少和增加。按下分配给一个变量的键会将另一个变量重置为零,因此当按下相反的按钮时下次调用该变量时,它将从零加速。一旦任一变量达到最大速度,释放按钮时它就会重置,这意味着角色可以再次加速。

如果有任何方法可以完成这项工作(如果可以的话,还可以整理代码),那么我们将非常感谢有关如何使其发挥作用的指导。

最佳答案

定义一个加速度变量(示例中的accel_x),在事件循环中将其设置为所需的值,并将其添加到每帧的x_change中以加速。要将x_change限制为最大速度,您必须对其进行归一化并将其乘以max_speed

要使对象减速,可以在未按下任何键时将 x_change 乘以小于 1 的值。

import pygame


pygame.init()
display = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
GRAY = pygame.Color('gray12')
display_width, display_height = display.get_size()
x = display_width * 0.45
y = display_height * 0.8
x_change = 0
accel_x = 0
max_speed = 6

crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
elif event.type == pygame.KEYDOWN:
# Set the acceleration value.
if event.key == pygame.K_LEFT:
accel_x = -.2
elif event.key == pygame.K_RIGHT:
accel_x = .2
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
accel_x = 0

x_change += accel_x # Accelerate.
if abs(x_change) >= max_speed: # If max_speed is exceeded.
# Normalize the x_change and multiply it with the max_speed.
x_change = x_change/abs(x_change) * max_speed

# Decelerate if no key is pressed.
if accel_x == 0:
x_change *= 0.92

x += x_change # Move the object.

display.fill(GRAY)
pygame.draw.rect(display, (0, 120, 250), (x, y, 20, 40))

pygame.display.update()
clock.tick(60)

pygame.quit()

关于python - Pygame - 运动加速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752275/

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