我正在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()
最佳答案
我不确定为什么要创建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.
关于python - 旋转时塑造“摆动”-Pygame,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53897002/