충돌 처리는 게임을 만드는 것에 있어서 꽤 중요한 부분 중 하나이다. 아무 처리를 하지 않았을때, 캐릭터 그림끼리 서로 겹치기도 하고 그냥 스쳐 지나간다. 그래서 이 캐릭터의 rigid 처리를 해주고, 서로 간의 충돌처리를 해주는 것이 중요하다. 이 파트를 잘 다룰 수 있다면, 벽돌깨기 게임도 만들 수 있고, 적군과 부딪쳤을때 또는 보물상자나 함정에 부딪쳤을 때, 어떤 이벤트를 발생시킬 수 있다.
여기에서는 피카츄가 몬스터볼에 부딪쳤을 때, 충돌처리를 하면서 게임을 종료시키는 작업을 진행해보자. 우선 그 전에 몬스터볼 이미지 파일도 불러오고, 셋팅하는 작업을 해줘야한다. 이것은 예전 캐릭터 셋팅 시 진행했던 작업과 거의 유사하다.
* 참고
https://bayleaf07.tistory.com/62
[추억의 오락실 게임 만들기] 2. 배경화면과 캐릭터 설정
보호되어 있는 글입니다. 내용을 보시려면 비밀번호를 입력하세요.
bayleaf07.tistory.com
▷ 전체코드 _ 몬스터볼 셋팅
더보기
#7. 충돌처리를 위한 셋팅
import pygame
pygame.init()
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
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/pika2.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
# 공 추가해주기
# 맨 처음에 캐릭터 만드는 과정과 거의 비슷
ball = pygame.image.load("C:/Users/Soyoung/Desktop/pygame/ball.jpg")
ball_size = ball.get_rect().size
ball_width = ball_size[0]
ball_height = ball_size[1]
ball_x_pos = (screen_width/2) - (ball_width/2)
ball_y_pos = (screen_height/2) - (ball_height/2)
to_x =0
to_y = 0
character_speed = 0.5
running = True
while running:
FPS = 60
dt = clock.tick(FPS)
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 -= character_speed
elif event.key == pygame.K_RIGHT:
to_x += character_speed
elif event.key == pygame.K_UP:
to_y -= character_speed
elif event.key == pygame.K_DOWN:
to_y += character_speed
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
# 보정을 해주기 위해서 dt의 값을 곱해준다.
# 그러면 캐릭터의 이동속도가 FPS의 영향을 덜 받게 해줄 수 있음
character_x_pos += to_x * dt
character_y_pos += to_y * dt
if character_x_pos < 0:
character_x_pos = 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))
# 공 그리기
screen.blit(ball,(ball_x_pos, ball_y_pos))
pygame.display.update()
pygame.quit()
셋팅을 다 진행하게 되면 아래와 같은 화면이 만들어진다. 지금은 몬스터 볼을 그냥 스쳐서 지나가는데,다음 시간에 여기에 충돌처리를 한번 해보도록 하자.



pika2.jpg
0.01MB
ball.jpg
0.00MB
▷ 참고 자료
'python으로 게임 만들기 > pygame' 카테고리의 다른 글
| [pygame] 9. 텍스트 글자 삽입 (0) | 2024.02.24 |
|---|---|
| [pygame] 8. 간단한 충돌처리 (0) | 2024.02.24 |
| [pygame] 6. FPS 설정2 (0) | 2024.02.24 |
| [pygame] 5. FPS 설정1 (0) | 2024.02.24 |
| [pygame] 4. 배경화면 경계선 처리 (0) | 2024.02.24 |