旋转时形状“摆动”-Pygame

时间:2018-12-22 15:36:33

标签: python pygame

我正在pygame上制作赛车游戏。它涉及汽车能够转弯,但转弯时,汽车会“摇摆”。如果您想知道我的意思,请运行下面的代码并按住箭头键之一。我不确定是什么问题,但我想保留redcar_pos = list(int(v) for v in pos_red) 行,因为这将有助于游戏的后期阶段,在此阶段,一旦汽车驶离赛道,游戏就会意识到这一点并做一些事情关于它。 pygame绘制的形状上的“摆动”可能不是很清楚,但是仍然很明显,但是我想在游戏中使用图像(我没有添加图像,因此可以更轻松地运行代码)和图像“摇摆”甚至更多。下面是该代码的简单版本。我希望有人可以帮助:)

import pygame
import pygame.freetype
from pygame.math import Vector2

pygame.init()
clock = pygame.time.Clock()
WIDTH = 900
HEIGHT = 550
screen = pygame.display.set_mode((WIDTH, HEIGHT))
REDCAR_ORIGINAL = pygame.Surface((50, 30), pygame.SRCALPHA)
redangle = 0
redspeed = 2
pos_red = Vector2(200, 200)
vel_red = Vector2(redspeed, 0)

redcar = REDCAR_ORIGINAL
pygame.draw.polygon(REDCAR_ORIGINAL, pygame.Color('dodgerblue'), [(0, 30), (50, 20), (50, 10), (0, 0)])
redrect = redcar.get_rect(center = pos_red)

run = True
while run:
  for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

  keys = pygame.key.get_pressed()
  if keys[pygame.K_LEFT]:
      redangle += 3
      vel_red.rotate_ip(-3)
      redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle)
      redrect = redcar.get_rect(center = redrect)
      mask_red = pygame.mask.from_surface(redcar)
  elif keys[pygame.K_RIGHT]:
      redangle -= 3
      vel_red.rotate_ip(3)
      redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle)
      mask_red = pygame.mask.from_surface(redcar)

  pos_red += vel_red
  redrect = pos_red

  redcar_pos = list(int(v) for v in pos_red)


  screen.fill(pygame.Color('green'))

  screen.blit(redcar, redcar_pos)
  pygame.display.flip()
  clock.tick(60)

pygame.quit()  

1 个答案:

答案 0 :(得分:1)

我不确定为什么要创建redcar_pos变量,因为您可以仅将redrect作为blit位置来传递。您也不应将pos_red分配给redrect,而应分配其center属性,否则redrect将是一个向量而不是pygame.Rect。

在旋转部分中,您可以只创建新的矩形,而无需传递中心坐标,因为pos_red(实际的中心坐标)将分配给每帧下方的redrect.center

这是我建议的更改:

if keys[pygame.K_LEFT]:
    redangle += 3
    vel_red.rotate_ip(-3)
    redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle)
    redrect = redcar.get_rect()  # No need to pass the previous center.
    mask_red = pygame.mask.from_surface(redcar)
elif keys[pygame.K_RIGHT]:
    redangle -= 3
    vel_red.rotate_ip(3)
    redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle)
    redrect = redcar.get_rect()  # Create a new rect here as well.
    mask_red = pygame.mask.from_surface(redcar)

pos_red += vel_red
redrect.center = pos_red  # Just assign the pos_red to the center.

screen.fill(pygame.Color('green'))

screen.blit(redcar, redrect)  # Blit it at the redrect.topleft coordinates.