Pyxel을 사용한 2D 게임 시작하기 (6부): 캐릭터 이동
Sure! I see the source line you’d like to keep unchanged, but I’ll need the actual article text you want translated. Could you please paste the content (or the portion you’d like translated) here? I’ll then provide the Korean translation while preserving the formatting, markdown, and code blocks as requested.
Source:
캐릭터 이동
이제 이전 장에서 만든 스프라이트를 실제로 움직일 차례입니다.
이번 장에서는 스프라이트에 속도 개념을 부여하고 간단한 이동 시스템을 구축합니다.
전체 코드는 이 글의 마지막에 표시됩니다.
1. Sprite 클래스 개선
먼저 공통 기반 클래스 BaseSprite를 강화합니다.
생성자에 두 개의 새로운 멤버 변수 vx와 vy를 추가합니다.
이 변수들은 update() 단계에서 스프라이트의 좌표 x와 y에 더해집니다.
이렇게 하면 캐릭터 위치가 조금씩 변하면서 게임 화면에서 움직이는 것처럼 보입니다.
또한 move()라는 새로운 메서드를 추가합니다. 이름 그대로 이 메서드는 이동을 시작합니다. 속도와 각도를 인수로 받습니다:
- 수평 성분(X 방향)은
math.cos()로 계산되어vx에 할당됩니다. - 수직 성분(Y 방향)은
math.sin()로 계산되어vy에 할당됩니다.
(아직 수학적 원리를 완전히 이해할 필요는 없습니다—괜찮아요!)
# sprite.py (excerpt)
class BaseSprite:
def __init__(self, x, y, w=8, h=8):
""" Constructor """
self.x = x
self.y = y
self.w = w
self.h = h
self.vx = 0 # Velocity (X direction)
self.vy = 0 # Velocity (Y direction)
def update(self):
""" Update logic """
self.x += self.vx # Move in X direction
self.y += self.vy # Move in Y direction
def draw(self):
""" Drawing logic (implemented in subclasses) """
pass
def move(self, spd, deg):
""" Start movement """
rad = deg * math.pi / 180
self.vx = spd * math.cos(rad) # X velocity
self.vy = spd * math.sin(rad) # Y velocity
2. 상수 정의
다음으로, main.py에 플레이어의 이동 속도를 나타내는 상수를 추가합니다. 값을 상수로 정의하면 나중에 조정하기가 훨씬 쉽습니다.
# main.py (add constants)
SHIP_SPD = 1.4 # Player speed
3. 스프라이트 이동 테스트
이제 스프라이트가 실제로 움직이는지 확인해 보겠습니다. Game 클래스의 생성자 안에서 테스트용으로 플레이어에게 이동 명령을 부여합니다.
# main.py (added to the Game class constructor)
# Test movement (toward the upper‑left)
self.ship.move(SHIP_SPD, 220)
각도 값을 바꿔 보면서 이동 방향도 바뀌는지 확인해 보세요.
Complete Code
Below is the complete code with all features implemented so far.
# sprite.py
import pyxel
import math
import random
class BaseSprite:
def __init__(self, x, y, w=8, h=8):
""" Constructor """
self.x = x
self.y = y
self.w = w
self.h = h
self.vx = 0 # Velocity (X direction)
self.vy = 0 # Velocity (Y direction)
def update(self):
""" Update logic """
self.x += self.vx # Move in X direction
self.y += self.vy # Move in Y direction
def draw(self):
""" Drawing logic (implemented in subclasses) """
pass
def move(self, spd, deg):
""" Start movement """
rad = deg * math.pi / 180
self.vx = spd * math.cos(rad) # X velocity
self.vy = spd * math.sin(rad) # Y velocity
class ShipSprite(BaseSprite):
def __init__(self, x, y):
""" Constructor """
super().__init__(x, y)
def draw(self):
""" Drawing logic """
pyxel.blt(
self.x, self.y, 0,
0, 0,
self.w, self.h, 0
) # Ship
# main.py
import pyxel
import math
import random
import sprite
W, H = 160, 120
SHIP_SPD = 1.4 # Player speed
# Game
class Game:
def __init__(self):
""" Constructor """
# Initialize score
self.score = 0
# Initialize player
self.ship = sprite.ShipSprite(W / 2, H - 40)
# Test movement (toward the upper‑left)
self.ship.move(SHIP_SPD, 220)
# Start Pyxel
pyxel.init(W, H, title="Hello, Pyxel!!")
pyxel.load("shooter.pyxres")
pyxel.run(self.update, self.draw)
def update(self):
""" Update logic """
# Update player
self.ship.update()
def draw(self):
""" Drawing logic """
pyxel.cls(0)
# Draw score
pyxel.text(
10, 10,
"SCORE:{:04}".format(self.score),
12
)
# Draw player
self.ship.draw()
def main():
""" Main entry point """
Game()
if __name__ == "__main__":
main()
프로그램을 실행하면 결과는 다음과 같이 표시됩니다:
다음에 올 내용…
이 장을 읽어 주셔서 감사합니다.
다음 제목은 “캐릭터 제어” 입니다.
다음에 또 만나요!!
