I've written some code that allows a image of a car to point and move towards the mouse cursor. I've managed to get all of the trigonometry working, and the program works. (Even if it is a bit clunky) But if I were to replace the image with a rectangle, how would I rotate it?
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)