1

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)    

Car

George Willcox
  • 677
  • 12
  • 30
  • you have to draw rectangle on `Surface()` (create image) and rotate surface. – furas Oct 09 '16 at 18:23
  • I'm not to familiar with surfaces, how would you do that? – George Willcox Oct 09 '16 at 18:24
  • 1
    `screen` is `Surface()`, `pygame.image.load()` returns `Surface()` - so you already use surfaces :) Create `new_surface = pygame.Surface()` and use it `new_surface.blit(image)` or `pygame.draw.rectange(new_surface,...)` – furas Oct 09 '16 at 18:27
  • BTW: you can keep rectangle as four points (corners) and draw it using four lines - then you can use math to calculate new position of points (corners). I would say you will have rectangle as "vector object" (and it is similar to OpenGL) – furas Oct 09 '16 at 18:31
  • 1
    I would also make a general function which allows you to blit an image using its centre rather than the topleft corner. The reason for that is that when you will rotate your image pygame will adjust the size of the rectangle which contains your image, so your image will appear to be a bit jumpy. – Sorade Oct 10 '16 at 12:13
  • @Sorade I'll keep that in mind – George Willcox Oct 10 '16 at 14:10

0 Answers0