gpt4 book ai didi

python - 我如何让我的角色加速和减速,而不仅仅是以一定的速度移动(在 pygame 中)?

转载 作者:行者123 更新时间:2023-12-04 09:15:27 26 4
gpt4 key购买 nike

有人能告诉我要改变什么,以便我的船使用推力力学而不是像现在这样的静态运动吗?
我希望运动就像在小行星中一样,它在你面对的方向上加速并且速度在某个点停止,然后如果你停止加速,它的速度会慢慢降低直到停止。
rn如果我按下前进按钮,它就会直接以最大速度开始移动,并在我松开时立即停止。
这是我的船类的代码

class Ship:
def __init__(self, x, y):
self.x = x
self.y = y
self.width = 0
self.vel = 0
self.angle = 0

def draw(self):
ship_img = pygame.image.load("sprites/ship_off.png")
ship_img_copy = pygame.transform.rotate(ship_img, self.angle)
window.blit(ship_img_copy,
(self.x - (ship_img_copy.get_width()) / 2, self.y - (ship_img_copy.get_height()) / 2))

keys = pygame.key.get_pressed()

if keys[pygame.K_w]:
ship_img = pygame.image.load("sprites/ship_on.png")
ship_img_copy = pygame.transform.rotate(ship_img, self.angle)
window.blit(ship_img_copy,
(self.x - (ship_img_copy.get_width()) / 2, self.y - (ship_img_copy.get_height()) / 2))

def move(self):
keys = pygame.key.get_pressed()
# todo acceleration and thrust mechanics
if keys[pygame.K_w]:
self.x += self.vel * cos(self.angle * (pi / 180) + (90 * pi / 180))
self.y -= self.vel * sin(self.angle * (pi / 180) + 90 * (pi / 180))
# So that if it leaves one side it comes from the other
if self.y < 0:
self.y = (self.y - self.vel) % 600

elif self.y > 600:
self.y = (self.y + self.vel) % 600

elif self.x < 0:
self.x = (self.x - self.vel) % 800

elif self.x > 800:
self.x = (self.x + self.vel) % 800

if keys[pygame.K_a]:
self.angle += 7

if keys[pygame.K_d]:
self.angle -= 7
我试过了,但我做不到,所以这是我的代码

最佳答案

你要改self.vel当按下 w 或 s 时,但您必须更改 self.xself.y在每一帧中,依赖于 self.vel :

class Ship:
def __init__(self, x, y):
# [...]

self.vel = 0
self.max_vel = 10

# [...]

def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.vel = min(self.vel+1, self.max_vel)
if keys[pygame.K_s]:
self.vel = max(self.vel-1, 0)

if keys[pygame.K_a]:
self.angle += 7
if keys[pygame.K_d]:
self.angle -= 7

self.x += self.vel * cos(self.angle * (pi / 180) + (90 * pi / 180))
self.y -= self.vel * sin(self.angle * (pi / 180) + 90 * (pi / 180))
if self.y < 0:
self.y = (self.y - self.vel) % 600
elif self.y > 600:
self.y = (self.y + self.vel) % 600
elif self.x < 0:
self.x = (self.x - self.vel) % 800
elif self.x > 800:
self.x = (self.x + self.vel) % 800

关于python - 我如何让我的角色加速和减速,而不仅仅是以一定的速度移动(在 pygame 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63245963/

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