Flip sprite when changing the direction of movement

Question:

Today I started to learn pygame and python to eventually remake the simple game "Graphwar".
As my first project I chose to make a really simple 2d car game while following a tutorial, now I want to try something on my own. That is to make my cars to visually change direction by using pygame.transform.flip() when pressing A or D.

I’ve read multiple different tutorials on different sites but I can’t get nothing to work.

This is my code:

#Imports
from turtle import pos
from xml.dom.pulldom import CHARACTERS
import pygame
import os

pygame.init()

#Colors
WHITE = (255,255,255)
BLACK = (0,0,0)
GREEN = (54, 236, 189)
GRAY = (64, 64, 64)

#Images
ICON = pygame.image.load(os.path.join("Assets", "icon.png"))
COOL = pygame.image.load(os.path.join("Assets", "cool.jpg"))
CAR1_IMG = pygame.image.load(os.path.join("Assets", "car1_sprite.png"))
CAR2_IMG = pygame.image.load(os.path.join("Assets", "car2_sprite.png"))

#Characters
CHARACTER_WIDTH = 252
CHARACTER_HEIGHT = 86
CAR1 = pygame.transform.scale(CAR1_IMG, (CHARACTER_WIDTH, CHARACTER_HEIGHT))
CAR2 = pygame.transform.scale(CAR2_IMG, (CHARACTER_WIDTH, CHARACTER_HEIGHT))

#Window
WIDTH, HEIGHT = 1280, 720
WIN=pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("USSPCS: Ultimate Super Supercar Policecar Chase Simulator Game of The Year Deluxe Edition")
pygame.display.set_icon(ICON)

FPS = 60
VEL = 3

#Render
def draw_window(CAR1_RECT, CAR2_RECT):
    WIN.fill(GRAY)
    WIN.blit(CAR1, (CAR1_RECT.x, CAR1_RECT.y)) #Draw CAR1
    WIN.blit(CAR2, (CAR2_RECT.x, CAR2_RECT.y)) #Draw CAR2
    pygame.display.update()

#Game
def main():
    CAR1_RECT = pygame.Rect(300, 100, CHARACTER_WIDTH, CHARACTER_HEIGHT) #CAR1 Hitbox
    CAR2_RECT = pygame.Rect(300, 300, CHARACTER_WIDTH, CHARACTER_HEIGHT) #CAR2 Hitbox
    
    clock = pygame.time.Clock()
    running = True
    while running:
        clock.tick(FPS)
        for event in pygame.event.get(): #Shutdown when clicking the X
            if event.type == pygame.QUIT:
                running = False
                
        if event.type == pygame.KEYDOWN: #Shutdown with ESC
            if event.key == pygame.K_ESCAPE:
             running = False
                
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_a]: #CAR1 Go left
            CAR1_RECT.x -= VEL
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_d]: #CAR1 Go right
            CAR1_RECT.x += VEL
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_w]: #CAR1 Go up
            CAR1_RECT.y -= VEL
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_s]: #CAR1 Go down
            CAR1_RECT.y += VEL
            
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_LEFT]: #CAR2 Go left
            CAR2_RECT.x -= VEL
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_RIGHT]: #CAR2 Go right
            CAR2_RECT.x += VEL
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_UP]: #CAR2 Go up
            CAR2_RECT.y -= VEL
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_DOWN]: #CAR2 Go down
            CAR2_RECT.y += VEL
        draw_window(CAR1_RECT, CAR2_RECT)
                
    pygame.quit()
    
if __name__ == "__main__":
    main()
Asked By: svasim

||

Answers:

Create 2 images for each care (e.g.: CAR_LEFT and CAR_RGIHT) and assign the image for the first direction to the variable `CAR1:

CAR1_RIGHT = pygame.transform.scale(CAR1_IMG, (CHARACTER_WIDTH, CHARACTER_HEIGHT))
CAR1_LEFT = pygame.transform.flip(CAR1_RIGHT, True, False)
CAR1 = CAR1_RIGHT 

Change the image when the button is pressed (Note that it is sufficient to call pygame.key.get_pressed() once in the application loop):

key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_a]: #CAR1 Go left
    CAR1_RECT.x -= VEL
    CAR1 = CAR1_LEFT
if key_pressed[pygame.K_d]: #CAR1 Go right
    CAR1_RECT.x += VEL
    CAR1 = CAR1_RIGHT 
Answered By: Rabbid76

I am working on a similar thing and my own is not working, the car won’t turn around, it only moves left, right, up, and down but wouldn’t turn around to face the opposite direction.

import pygame
import os

WHITE = (255, 255, 255)

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Avoid Obstacles")

BACKGROUND_IMAGE = pygame.image.load(
   os.path.join("Assets", "road.png"))

CAR_IMAGE = pygame.image.load(
 os.path.join("Assets", "carone.png"))
TURNING = 3.2


class AvoidObstacles:

def __init__(self, x, y, car_width, car_height):
    self.x = x
    self.y = y
    self.car_width = car_width
    self.car_height = car_height

def draw_window(self, car):
    CAR_ONE = pygame.transform.scale(
        CAR_IMAGE, (self.car_width, self.car_height))
    WIN.fill(WHITE)

    WIN.blit(pygame.transform.scale(
        BACKGROUND_IMAGE, (WIDTH, HEIGHT)), (0, 0))
    WIN.blit(CAR_ONE, (car.x, car.y))
    pygame.display.update()

def handles_car_movement(self, keys_pressed, car):
    if(keys_pressed[pygame.K_LEFT]):  # Turn LEFT KEY
        car.x -= TURNING
        self.car_width += 3

    if(keys_pressed[pygame.K_RIGHT]):  # Turn RIGHT KEY
        car.x += TURNING

def main(self):
    clock = pygame.time.Clock()

    carWithPosition = pygame.Rect(
        self.x, self.y, self.car_width, self.car_height)

    run = True
    while run:
        clock.tick(60)
        for event in pygame.event.get():
            keys_pressed = pygame.key.get_pressed()
            self.handles_car_movement(keys_pressed, carWithPosition)
            if event.type == pygame.QUIT:
                run = False
        self.draw_window(carWithPosition)
    pygame.quit()


  avoidObostacle = AvoidObstacles(500, 300, 55, 40)

 if(__name__ == "__main__"):
   avoidObostacle.main()
Answered By: Chukwuma Kingsley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.