我写了一些代码,允许汽车的图像指向并移向鼠标光标。我设法使所有的三角函数都能正常工作,程序也可以运行。 (即使它有点笨拙)但是如果我用矩形替换图像,我将如何旋转它?
import sys, pygame, math
from pygame.locals import *
pygame.init()
SCREEN = pygame.display.set_mode((800, 600))
CrossHair = pygame.image.load('Crosshair.png').convert_alpha()
image = pygame.image.load('Car.png').convert_alpha()
pygame.display.set_caption('Car')
pygame.display.set_icon(image)
CLOCK = pygame.time.Clock()
pygame.mouse.set_visible(False)
def Quit():
'''Shuts down the game if it's closed'''
for event in pygame.event.get():
if event.type == QUIT:
print('Quit the game...')
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
print('Quit the game...')
pygame.quit()
sys.exit()
carX, carY = 400, 300
angle = 0
speed = 0
while True:
Quit()
SCREEN.fill((225, 255, 255))
pos = pygame.mouse.get_pos()
angle = 360 - math.atan2(pos[1] - carY, pos[0] - carX) * 180 / math.pi
rotimage = pygame.transform.rotate(image, angle)
rect = rotimage.get_rect(center = (carX, carY))
if pygame.mouse.get_pressed()[0]:
speed += 1
if pygame.mouse.get_pressed()[2]:
speed -= 0.2
speed *= 0.95
carX += speed * math.cos(math.radians(angle))
carY -= speed * math.sin(math.radians(angle))
SCREEN.blit(rotimage, rect)
SCREEN.blit(CrossHair, (pos))
pygame.display.update()
CLOCK.tick(30)