배경화면의 경계선을 처리하기 위해서는, 먼저 배경화면과 캐릭터의 x좌표, y좌표의 값을 잘 알아야합니다. 그래서 먼저 코드로 구현해보기 전에 종이나 펜으로 그림을 그려보는 과정이 필요합니다.
코드 구현 과정은 다음과 같습니다.
# 가로 경계값 처리
# 캐릭터 위치가 0보다 작아지면, 그 자리에 멈춰있게 처리
if character_x_pos < 0:
character_x_pos = 0
# 캐릭터 위치가 오른쪽 벽을 넘어가지 못하게 처리
# 배경화면이랑 캐릭터랑 기준이 (0,0)이니까 그걸 고려한 것
elif character_x_pos > screen_width - character_width:
character_x_pos = screen_width - character_width
# 세로 경계값 처리
# 캐릭터가 위로 가지 못하게
if character_y_pos < 0:
character_y_pos = 0
# 캐릭터가 아래로 내려가지 못하게
elif character_y_pos > screen_height - character_height:
character_y_pos = screen_height - character_height
▷ 배경화면 경계선 처리 결과
아주 잘 됩니다. 피카츄가 밖으로 나가지 않아요
▷ 전체코드 _ 배경화면 경계선 처리
더보기
#4. 배경화면 경계선 처리
import pygame
pygame.init()
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Let's make game")
background = pygame.image.load("C:/Users/Soyoung/Desktop/pygame/background.png")
character = pygame.image.load("C:/Users/Soyoung/Desktop/pygame/pika.jpg")
character_size = character.get_rect().size
character_width = character_size[0]
character_height = character_size[1]
character_x_pos = (screen_width/2) - (character_width/2)
character_y_pos = screen_height - character_height
to_x =0
to_y = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
to_x -= 0.05
elif event.key == pygame.K_RIGHT:
to_x += 0.05
elif event.key == pygame.K_UP:
to_y -= 0.05
elif event.key == pygame.K_DOWN:
to_y += 0.05
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
to_x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
to_y = 0
character_x_pos += to_x
character_y_pos += to_y
# 가로 경계값 처리
# 캐릭터 위치가 0보다 작아지면, 그 자리에 멈춰있게 처리
if character_x_pos < 0:
character_x_pos = 0
# 캐릭터 위치가 오른쪽 벽을 넘어가지 못하게 처리
# 배경화면이랑 캐릭터랑 기준이 (0,0)이니까 그걸 고려한 것
elif character_x_pos > screen_width - character_width:
character_x_pos = screen_width - character_width
# 세로 경계값 처리
# 캐릭터가 위로 가지 못하게
if character_y_pos < 0:
character_y_pos = 0
# 캐릭터가 아래로 내려가지 못하게
elif character_y_pos > screen_height - character_height:
character_y_pos = screen_height - character_height
screen.blit(background, (0,0))
screen.blit(character,(character_x_pos, character_y_pos))
pygame.display.update()
pygame.quit()
▷ 참고 자료
나도 코딩 : https://www.youtube.com/watch?v=Dkx8Pl6QKW0
봄날의 자전거 : https://www.youtube.com/watch?v=EBHwe5RCJEc
'python으로 게임 만들기 > pygame' 카테고리의 다른 글
[pygame] 6. FPS 설정2 (0) | 2024.02.24 |
---|---|
[pygame] 5. FPS 설정1 (0) | 2024.02.24 |
[pygame] 3. 키보드 이벤트 (0) | 2024.02.24 |
[pygame] 2. 배경화면과 캐릭터 설정 (0) | 2024.02.24 |
[pygame] 1. 기본 설정 (0) | 2024.02.24 |