[python] pygame 움직이는 오브젝트

오브젝트를 생성하고 오브젝트에 속도 벡터 정보를 주고 오브젝트가 움직이도록 해 보겠습니다. 속도 벡터를 정의하는 방법중에 기준선 대비 방향의 각도와 속도의 스칼라값으로 정의하는 방법을 사용할 것이며, 아래 그림을 참조했습니다.


랜덤하게 생성된 속도 벡터를 가진 원형 모양의 오브젝트를 생성하고 움직이게 할 것입니다. 화면 경계에서 반사되는 기능은 아래 내용을 참조하였습니다.


아래는 구현된 파이썬 코드입니다.


import pygame
import random
import math

class Particle():
    def __init__(self, position, size):
        self.x, self.y = position
        self.size = size
        self.colour = (0, 0, 255)
        self.thickness = 1
        self.speed = 0
        self.angle = 0

    def display(self):
        pygame.draw.circle(screen, self.colour, (int(self.x), int(self.y)), self.size, self.thickness)

    def move(self, df):
        # df : 초당 프레임 수 (FPS에 따른 위치 보정)
        self.x += math.sin(self.angle) * self.speed * df
        self.y -= math.cos(self.angle) * self.speed * df

    def bounce(self):
        if self.x > width - self.size:
            self.x = 2*(width - self.size) - self.x
            self.angle = - self.angle

        elif self.x < self.size:
            self.x = 2*self.size - self.x
            self.angle = - self.angle

        if self.y > height - self.size:
            self.y = 2*(height - self.size) - self.y
            self.angle = math.pi - self.angle

        elif self.y < self.size:
            self.y = 2*self.size - self.y
            self.angle = math.pi - self.angle

# 윈도우 타이틀
pygame.display.set_caption('Tutorial 5')

# 배경화면 색상
background_color = (255,255,255)

# 윈도우 사이즈
(width, height) = (400, 400)
screen = pygame.display.set_mode((width, height))

# FPS 설정
clock = pygame.time.Clock()

# 파티클 생성
number_of_particles = 10
my_particles = []

for n in range(number_of_particles):
    size = random.randint(10, 20)
    x = random.randint(size, width-size)
    y = random.randint(size, height-size)

    particle = Particle((x, y), size)
    particle.speed = random.random()
    particle.angle = random.uniform(0, math.pi*2)

    my_particles.append(particle)
    
running = True
while running:
    df = clock.tick(60)

    for event in pygame.event.get():
        # 닫기 버튼 감지
        if event.type == pygame.QUIT:
            running = False
        
    screen.fill(background_color)

    for particle in my_particles:
        particle.move(df)
        particle.bounce()
        particle.display()

    pygame.display.flip()




아래는 실행결과입니다.


끝.

댓글

이 블로그의 인기 게시물

[PLC] PLC 아날로그 입출력 기본

NPN, PNP 트랜지스터 차이점

전력(kW) 계산하기 (직류, 교류 단상, 교류 삼상)

제너 다이오드에 저항을 연결하는 이유

3선 결선식 센서의 타입 PNP, NPN

[아두이노] 가변저항(Potential Divider)과 전압분배(Voltage Divider)

커패시터에 저장된 에너지 계산

3상 모터 전력에서 전류 계산하기 (How to Convert Three-Phase Power to Amps)

[공압밸브] 5포트 2웨이 & 4포트 2웨이, 단동 VS 복동 차이점

[PLC] PLC 입출력 타입 - 싱크 & 소스 (Sink & Source)