gpt4 book ai didi

python - 我如何让汽车朝它指向的方向移动(在使用 pygame.translation.rotate 之后)

转载 作者:行者123 更新时间:2023-11-28 22:51:05 26 4
gpt4 key购买 nike

好吧,我正在做一个赛车游戏的测试......我希望汽车朝它指向的方向移动。这是我的代码。

import pygame, sys
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()
degree = 0
WHITE = 250,250,250
rect2 = pygame.rect = (100,100,50,50)
WINDOWWIDTH = 1200
WINDOWHEIGHT = 750
thing = pygame.image.load('car.png')
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Teh test')
left = False
right = False
while True:
rect2 = pygame.rect = (100,100,50,50)
if right == True:
degree -= 2
if left == True:
degree += 2
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('a'):
left = True
if event.key == ord('d'):
right = True
if event.type == KEYUP:
if event.key == ord('a'):
left = False
if event.key == ord('d'):
right = False
pygame.draw.rect(screen,WHITE,rect2)
screen.fill((40, 40, 40))
thing2 = pygame.transform.rotate(thing,degree)
screen.blit(thing2,(100,100))
pygame.display.update()
mainClock.tick(60)

就像我说的那样,我想知道如何让汽车朝它指向的方向移动。我试图想办法,但我想不出任何办法。所以真的没有什么可以纠正的。(如果有任何问题,我会编辑我的问题来回答它。)请确保您在回答之前了解 pygame。

最佳答案

您需要使用三角函数来计算您希望在 x 和 y 方向上移动多少,以便汽车最终朝正确的方向移动。要计算这个,您可以这样做:

dx = math.cos(math.radians(degree))
dy = math.sin(math.radians(degree))
position = (position[0] + dx * SPEED, position[1] - dy * SPEED)

请注意,您还需要在代码开头的某处初始化位置变量,如下所示:

position = (100, 100)

然后,您必须更改 blit 代码行,以便始终在位置变量处绘制,而不是始终在 (100, 100) 处绘制:

screen.blit(thing2, position)

编辑:工作示例

import pygame, sys
from pygame.locals import *
import math
pygame.init()
mainClock = pygame.time.Clock()
degree = 0
WHITE = 250,250,250
rect2 = pygame.rect = (100,100,50,50)
WINDOWWIDTH = 1200
WINDOWHEIGHT = 750
thing = pygame.image.load('car.png')
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Teh test')
left = False
right = False
position = (100, 100)
while True:
rect2 = pygame.rect = (100,100,50,50)
if right == True:
degree -= 2
if left == True:
degree += 2
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('a'):
left = True
if event.key == ord('d'):
right = True
if event.type == KEYUP:
if event.key == ord('a'):
left = False
if event.key == ord('d'):
right = False
pygame.draw.rect(screen,WHITE,rect2)
screen.fill((40, 40, 40))
thing2 = pygame.transform.rotate(thing,degree)
dx = math.cos(math.radians(degree))
dy = math.sin(math.radians(degree))
position = (position[0] + dx, position[1] - dy)
screen.blit(thing2, position)
pygame.display.update()
mainClock.tick(60)

关于python - 我如何让汽车朝它指向的方向移动(在使用 pygame.translation.rotate 之后),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056805/

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