본문 바로가기
파이썬/파이게임(Pygame)

[파이게임.006]충돌 감지하기

by 긱펀 2022. 6. 14.
반응형

🚩 움직이는 이미지의 충돌 구현하기

[1] 미리보기

움직이는 이미지의 충돌 구현하기

 

[2] 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# 이번시간내용 : 충돌감지 , 점수내기
import pygame
 
# pygame window setup
pygame.init()
background = pygame.display.set_mode((480,360))
pygame.display.set_caption("image")
 
# image load
image_bg = pygame.image.load("image/Blue Sky.svg"# 이미지 불러오기
image_ball = pygame.image.load("image/ball.png")
image_ball = pygame.transform.scale(image_ball,(48,48)) # 이미지 크기조절
image_dog = pygame.image.load("image/dog.png")
image_dog = pygame.transform.scale(image_dog, (80,80))
 
# some variables
size_bg_width = background.get_size()[0]
size_bg_height = background.get_size()[1]
 
size_ball_width = image_ball.get_rect().size[0]
size_ball_height = image_ball.get_rect().size[1]
 
x_pos_ball = size_bg_width/2 - size_ball_width/2
y_pos_ball = 0
 
size_dog_width = image_dog.get_rect().size[0]
size_dog_height = image_dog.get_rect().size[1]
 
x_pos_dog = size_bg_width/2 - size_dog_width/2
y_pos_dog = size_bg_height - size_dog_height
 
# dog를 방향키로 움직이기 위한 추가
to_x = 0
to_y = 0
dog_speed = 1
 
# ball이 자동으로 움직이기 위한 추가
x_speed_ball = 1
y_speed_ball = 1
 
# make a window with ALL
play = True
while play:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            play = False
        if event.type == pygame.KEYDOWN: #키보드를 눌렀다면
            # 좌우로만 dog를 움직이기
            if event.key == pygame.K_RIGHT: #오른쪽 화살표키 라면
                to_x = dog_speed
            elif event.key == pygame.K_LEFT: #왼쪽 화살표키 라면
                to_x = -dog_speed
        
        if event.type == pygame.KEYUP: #키보드를 뗏다면
            if event.key == pygame.K_RIGHT: #오른쪽 화살표키 라면
                to_x = 0
            elif event.key == pygame.K_LEFT: #왼쪽 화살표키 라면
                to_x = 0
    # end of for
 
    # dog가 좌우 벽에서 팅기기 #
    if x_pos_dog < 0:
        x_pos_dog = 0
    elif x_pos_dog > size_bg_width - size_dog_width:
        x_pos_dog = size_bg_width - size_dog_width
    else:
        x_pos_dog += to_x
 
    # 추가 (5) #
    x_pos_ball += x_speed_ball
    y_pos_ball += y_speed_ball
    # 추가 (5)를 중간실행해 보면, 공이 쭉 떨어지는걸 확인할수 있음
    
    # 추가 (6) 공이 테두리에서 튕기게 하기 #
    if x_pos_ball <= 0:
        print("왼쪽벽")
        x_pos_ball = 0
        x_speed_ball = -x_speed_ball # 추가(7) 4면에서 튕기게하기
    elif x_pos_ball >= size_bg_width - size_ball_width:
        print("오른쪽벽")
        x_pos_ball = size_bg_width - size_ball_width
        x_speed_ball = -x_speed_ball # 추가(7)
    
    if y_pos_ball <= 0:
        print("천장")
        y_pos_ball = 0
        y_speed_ball = -y_speed_ball # 추가(7)
    elif y_pos_ball >= size_bg_height - size_ball_height:
        print("바닥")
        y_pos_ball = size_bg_height - size_ball_height
        y_speed_ball = -y_speed_ball # 추가(7)
    # 추가 (6)을 중간실행해 보면, 공이 벽에 부딪힌 뒤 쭉 미끌어짐
 
 
    ###### ball이 dog에 닿으면 튕기게 하는 <추가 코딩 시작> #######
    # 파이썬의 image는 눈에 보이지 않는 사각형(rect)이 존재/사각형 충돌로 감지
    rect_ball = image_ball.get_rect() # ball의 rect를 변수에 저장
    rect_ball.left = x_pos_ball # 사각형도 이미지 따라 움직이게 좌표 넣어주기
    rect_ball.top = y_pos_ball # 사각형도 이미지 따라 움직이게 좌표 넣어주기
 
    rect_dog = image_dog.get_rect() # dog의 rect를 변수에 저장
    rect_dog.left = x_pos_dog
    rect_dog.top = y_pos_dog
 
    # 충돌감지
    if rect_dog.colliderect(rect_ball): # 충돌이 되었나?
        print("충돌됨")
        x_speed_ball = -x_speed_ball # -로 바꾸면 반대로 튕긴다.
        y_speed_ball = -y_speed_ball # -로 바꾸면 반대로 튕긴다.
 
    ################ <추가 코딩 끝> #####################
 
 
    # blit(이미지 객체, 이미지 좌표): 이미지를 화면에 나타내기
    background.blit(image_bg, (0,0))
    #background.blit(image_dog, (0,0))
    background.blit(image_dog, (x_pos_dog, y_pos_dog))
    background.blit(image_ball, (x_pos_ball, y_pos_ball))
    pygame.display.update()
 
pygame.quit()
 
cs
728x90
반응형

댓글