How to move the background image with keys in pygame?

江枫思渺然 提交于 2021-02-12 09:20:20

问题


I am making a game in pygame. In this game, the background image is large. On the screen, player only sees about 1/20th of the background image. I want, when player presses the left, right, up or down arrow keys, the background image moves respectively, but, it stops moving when player reaches the end of the image. I have no idea how to do this.

My code up to this point :-

import pygame

FPS = 60
screen = pygame.display.set_mode((1000, 1000))
bg = pygame.image.load('map.png')

clock = pygame.time.Clock()

while True:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

Thanks in Advance :-


回答1:


Get the sice of the background and the screen by get_size():

screen_size = screen.get_size()
bg_size = bg.get_size()

Define the initial start of the background in range [0, bg_size[0]-screen_size[0]]. e.g. center of the background:

bg_x = (bg_size[0]-screen_size[0]) // 2

Get the list of the key states by pygame.key.get_pressed():

keys = pygame.key.get_pressed()

Change bg_x dependent on the state of left and right:

if keys[pygame.K_LEFT]:
    bg_x -= 10
if keys[pygame.K_RIGHT]:
    bg_x += 10

Clamp bg_x to the range [0, bg_size[0]-screen_size[0]]:

 bg_x = max(0, min(bg_size[0]-screen_size[0], bg_x))

blit the background at -bg_x on the screen:

screen.blit(bg, (-bg_x, 0))

See the example:

import pygame

FPS = 60
screen = pygame.display.set_mode((1000, 1000))
bg = pygame.image.load('map.png')

screen_size = screen.get_size()
bg_size = bg.get_size()
bg_x = (bg_size[0]-screen_size[0]) // 2
bg_y = (bg_size[1]-screen_size[1]) // 2

clock = pygame.time.Clock()

while True:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        bg_x -= 10
    if keys[pygame.K_RIGHT]:
        bg_x += 10
    if keys[pygame.K_UP]:
        bg_y -= 10
    if keys[pygame.K_DOWN]:
        bg_y += 10
    bg_x = max(0, min(bg_size[0]-screen_size[0], bg_x)) 
    bg_y = max(0, min(bg_size[1]-screen_size[1], bg_y))

    screen.blit(bg, (-bg_x, -bg_y))
    pygame.display.flip()


来源:https://stackoverflow.com/questions/61039508/how-to-move-the-background-image-with-keys-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!