Lecture Rect 함수

Lecture • Views 48 • Comments 0 • Last Updated at 1 week ago  
  • Rect
  • Rect

Rect

Rect 객체는 객체들의 충돌을 탐지하는 다양한 방법을 제공한다.

collidepoint

스크린의 임의의 점을 마우스로 클릭하면 그 점이 사각형 안에 있는지 여부를 판단한다.

import pygame

# Window size
WINDOW_WIDTH=400
WINDOW_HEIGHT=400
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("Point Collision")

BLACK = (  50,  50,  50 )
GREEN = (  34, 139,  34 )
BLUE  = ( 161, 255, 254 )

# The rectangle to click-in
# It is window-centred, and 33% the window size
click_rect  = pygame.Rect( WINDOW_WIDTH//3, WINDOW_HEIGHT//3, WINDOW_WIDTH//3, WINDOW_HEIGHT//3 )
rect_colour = BLACK

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle all the events
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.MOUSEBUTTONUP ):
            mouse_position = pygame.mouse.get_pos()             # Location of the mouse-click
            if ( click_rect.collidepoint( mouse_position ) ):   # Was that click inside our rectangle 
                print( "hit" )
                # Flip the colour of the rect
                if ( rect_colour == BLACK ):
                    rect_colour = GREEN
                else:
                    rect_colour = BLACK
            else:
                print( "click-outside!" )
    # update the screen
    window.fill( BLUE )
    pygame.draw.rect( window, rect_colour, click_rect)  # DRAW OUR RECTANGLE
    pygame.display.flip()
    # Clamp the FPS to an upper-limit
    clock.tick_busy_loop( 60 )
pygame.quit()

마우스가 사각형 안으로 들어가면 빨간색으로 나가면 흰색으로 바뀐다.

import pygame
pygame.init()
window = pygame.display.set_mode((250, 250))
rect = pygame.Rect(*window.get_rect().center, 0, 0).inflate(100, 100)
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    point = pygame.mouse.get_pos()
    collide = rect.collidepoint(point)
    color = (255, 0, 0) if collide else (255, 255, 255)
    window.fill(0)
    pygame.draw.rect(window, color, rect)
    pygame.display.flip()
pygame.quit()

colliderect

마우스 위치를 중심으로 사각형2가 만들어지고 사각형1과 충돌되는지 확인한다.

import pygame

pygame.init()
window = pygame.display.set_mode((250, 250))
rect1 = pygame.Rect(*window.get_rect().center, 0, 0).inflate(75, 75)
rect2 = pygame.Rect(0, 0, 75, 75)

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    rect2.center = pygame.mouse.get_pos()
    collide = rect1.colliderect(rect2)
    color = (255, 0, 0) if collide else (255, 255, 255)
    window.fill(0)
    pygame.draw.rect(window, color, rect1)
    pygame.draw.rect(window, (0, 255, 0), rect2, 6, 1)
    pygame.display.flip()
pygame.quit()
first article
last article
Comments
Feel free to ask a question, answer or comment, etc.