我正在尝试使用pygame在python上制作游戏,该游戏由互相射击的坦克组成。我有一个问题,当我试图将Sprite旋转90度时,速度太快了,我需要使它像这样,一旦您按下按钮,它就会倾斜90度,然后它可以朝那个方向移动< / p>
我已经尝试过使用带有true和false的if语句,但这在应该使停止角度达到90度时仍会使其倾斜得太快。
更新功能基本上是在位置上增加速度,而绘制功能则根据对象的位置将对象放到屏幕上。
这是代码段:
class Tank:
def __init__(self, x, y, pic):
self.xpos = x
self.ypos = y
self.speed_x = 0
self.speed_y = 0
self.picture = pic
self.rotation_angle = 0
self.rotation_angle_speed = 0
self.rect = self.picture.get_rect()
def update(self):
self.xpos =+ self.speed_x
self.ypos =+ self.speed_y
self.rotation_angle =+ self.rotation_angle_speed
def rotate(self):
self.picture = pygame.transform.rotate(self.picture, self.rotation_angle)
def draw(self):
screen.blit(self.picture, (self.xpos, self.ypos))
def is_collided_with(self, sprite):
return self.rect.colliderect(sprite.rect)
one_tank = pygame.image.load("C:/aliens/tank_two.png").convert_alpha()
one_tank = pygame.transform.scale(one_tank, (100, 100))
tank_one = Tank(100, 100, one_tank)
level = Level_background(0, 0, level_pic)
one_right = False
one_left = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
tank_one.speed_y = -5
elif event.key == pygame.K_s:
tank_one.speed_y = 5
elif event.key == pygame.K_a:
tank_one.speed_x = -5
elif event.key == pygame.K_d:
tank_one.speed_x = 5
elif event.key == pygame.K_q:
if one_left == False:
tank_one.rotation_angle_speed = -90
one_left = True
elif event.key == pygame.K_e:
if one_right == False:
tank_one.rotation_angle_speed = 90
one_right = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_w:
tank_one.speed_y = 0
elif event.key == pygame.K_s:
tank_one.speed_y = 0
elif event.key == pygame.K_a:
tank_one.speed_x = 0
elif event.key == pygame.K_d:
tank_one.speed_x = 0
elif event.key == pygame.K_q:
if one_left == True:
tank_one.rotation_angle_speed = 0
one_left = False
elif event.key == pygame.K_e:
if one_right == True:
tank_one.rotation_angle_speed = 0
one_right = False
tank_one.update()
level.draw()
tank_one.rotate()
tank_one.draw()
pygame.display.flip()
clock.tick(60)
我希望它可以倾斜90度并保持那样,直到再次单击该按钮。但是相反,它只是决定倾斜大约90度以上
答案 0 :(得分:0)
旋转90度后,请重置控制旋转的参数。只要没有按下新按钮,这将导致不再应用进一步的旋转:
class Tank:
# [...]
def rotate(self):
self.picture = pygame.transform.rotate(self.picture, self.rotation_angle)
self.rotation_angle_speed = 0
self.rotation_angle = 0
此外,类update
的方法Tank
中存在问题。 =+
将分配一个值。注意=
是赋值,+
只是该值的正号。增量分配是+=
而不是=+
:
class Tank:
# [...]
def update(self):
self.xpos += self.speed_x
self.ypos += self.speed_y
# [...]
此外,您应该在每一帧开始时清除整个窗口。这可以通过pygame.Surface.fill()
完成:
while True:
screen.fill((0,0,0))
# [...]