Akhil Anand Sirra
Akhil Anand Sirra

Reputation: 59

Move background with the player in all directions

This is my first game in Python. I wanted it to move the background with my player, while player position remains fixed in the middle and moving the background in all directions and make it look and feel like player is moving.

This my background image.

This is my game screen.

As you can see player is in the middle, enemies follow the player and tries to shoot the enemies, I got the movement of player and enemies correctly.

The enemies move opposite to the keys pressed, but the background doesn't move with it so the movement is not synced with enemies.

I tried using moving the background screen.blit(), if keys are pressed background changes it coordinates accordingly.

import math
import random
import os
import pygame as pg
import sys


pg.init()
height = 650
width = 1200

x1 = 0
y1 = 0
x2 = 0
y2 = 0


screen = pg.display.set_mode((width, height), pg.NOFRAME)
screen_rect = screen.get_rect()
background = pg.image.load('background.png').convert()
background = pg.transform.smoothscale(pg.image.load('background.png'), (width, height))
clock = pg.time.Clock()
running = True

game_over = True
start = True

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            sys.exit()
            pygame.quit()

#To make the background move
    key = pg.key.get_pressed()
    dist = 1
    if key[pg.K_DOWN] or key[pg.K_s]:  # down key
        y2 += dist 
    elif key[pg.K_UP] or key[pg.K_w]:  # up key
        y2 -= dist 
    if key[pg.K_RIGHT] or key[pg.K_d]:  # right key
        x2 += dist 
    elif key[pg.K_LEFT] or key[pg.K_a]:  # left key
        x2 -= dist  

    screen.blit(background, [x1, y1])
    screen.blit(background, [x2, y2])
    all_sprites.update()
    all_sprites.draw(screen)
    clock.tick(60)
    pg.display.update()

Even after trying to move the background, movement doesn't feel right.

Upvotes: 0

Views: 675

Answers (1)

Pythenx
Pythenx

Reputation: 72

You should consider getting another background image, because even if you get the background moving right, there will always be a distinct seperation between the images. You could consider making the same background image much larger and show only a portion of it at a time, but this way there will be map boundaries, which you probably don't want. Try finding/making background image which would transition smoother, so there wouldn't be that ugly distinct seperation line between images. Anyways you can look at pygame_functions which will make working with sprites and scrolling backgrounds much easier. If you find a better background image, I can help making it scroll. Hope this helps.

Upvotes: 1

Related Questions