아래는 HTML5 캔버스와 순수 JavaScript를 이용해 간단한 도트형 RPG 오픈월드 느낌의 게임을 구현한 예제입니다. 이 예제는 무작위로 생성된 타일맵 위에서 빨간색 플레이어가 화살표(또는 WASD) 키로 이동하며 카메라가 플레이어를 따라 움직이는 형태로 동작합니다. 실제 게임처럼 기능이 풍부하지는 않지만, 기본적인 구조와 화면 갱신, 카메라 이동, 타일 그리기, 플레이어 이동 등을 포함하고 있어 확장할 수 있는 토대가 될 것입니다.
아래 코드를 HTML 파일로 저장하고 브라우저로 실행해 보세요.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>도트형 RPG 오픈월드 게임 예제</title>
<style>
/* 브라우저 여백 제거 및 캔버스 중앙 정렬 */
body {
margin: 0;
overflow: hidden;
background: #333;
}
canvas {
display: block;
margin: 0 auto;
background: #000;
}
</style>
</head>
<body>
<!-- 게임 화면을 보여줄 캔버스 -->
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
// 캔버스 및 컨텍스트 설정
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// 타일과 지도 관련 설정
const tileSize = 32; // 각 타일의 크기(px)
const mapWidth = 100; // 지도 가로 타일 수
const mapHeight = 100; // 지도 세로 타일 수
const map = [];
// 간단한 무작위 타일맵 생성
// 0: 초원(풀), 1: 흙
for (let y = 0; y < mapHeight; y++) {
map[y] = [];
for (let x = 0; x < mapWidth; x++) {
// 대체로 초원 타일, 가끔 흙 타일 생성
map[y][x] = Math.random() > 0.1 ? 0 : 1;
}
}
// 카메라 객체: 플레이어를 따라 이동
const camera = {
x: 0,
y: 0,
width: canvas.width,
height: canvas.height
};
// 플레이어 객체: 게임 내 이동 캐릭터 (빨간 사각형으로 표현)
const player = {
x: (mapWidth * tileSize) / 2,
y: (mapHeight * tileSize) / 2,
width: 28,
height: 28,
speed: 2
};
// 키 입력 상태 저장
const keys = {};
window.addEventListener("keydown", (e) => { keys[e.key] = true; });
window.addEventListener("keyup", (e) => { keys[e.key] = false; });
// 업데이트: 플레이어 이동 및 카메라 위치 갱신
function update() {
// 키 입력에 따라 플레이어 이동 (WASD 또는 화살표)
if (keys["ArrowUp"] || keys["w"] || keys["W"]) player.y -= player.speed;
if (keys["ArrowDown"] || keys["s"] || keys["S"]) player.y += player.speed;
if (keys["ArrowLeft"] || keys["a"] || keys["A"]) player.x -= player.speed;
if (keys["ArrowRight"] || keys["d"] || keys["D"]) player.x += player.speed;
// 플레이어가 지도밖으로 나가지 않도록 제한
if (player.x < 0) player.x = 0;
if (player.y < 0) player.y = 0;
if (player.x > mapWidth * tileSize - player.width)
player.x = mapWidth * tileSize - player.width;
if (player.y > mapHeight * tileSize - player.height)
player.y = mapHeight * tileSize - player.height;
// 카메라를 플레이어 중앙으로 이동시키기
camera.x = player.x + player.width / 2 - camera.width / 2;
camera.y = player.y + player.height / 2 - camera.height / 2;
// 카메라가 지도 영역을 벗어나지 않도록 제한
if (camera.x < 0) camera.x = 0;
if (camera.y < 0) camera.y = 0;
if (camera.x > mapWidth * tileSize - camera.width)
camera.x = mapWidth * tileSize - camera.width;
if (camera.y > mapHeight * tileSize - camera.height)
camera.y = mapHeight * tileSize - camera.height;
}
// 그리기: 배경 타일과 플레이어를 캔버스에 렌더링
function draw() {
// 전체 캔버스 클리어
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 현재 카메라 영역 내에 보이는 타일 범위 계산
const startCol = Math.floor(camera.x / tileSize);
const endCol = startCol + Math.ceil(camera.width / tileSize);
const startRow = Math.floor(camera.y / tileSize);
const endRow = startRow + Math.ceil(camera.height / tileSize);
// 타일 그리기
for (let row = startRow; row <= endRow; row++) {
for (let col = startCol; col <= endCol; col++) {
// 지도 경계 검사
if (row < 0 || row >= mapHeight || col < 0 || col >= mapWidth) continue;
const tile = map[row][col];
if (tile === 0) {
ctx.fillStyle = "#7cfc00"; // 초원: 연두색
} else if (tile === 1) {
ctx.fillStyle = "#8b4513"; // 흙: 갈색
} else {
ctx.fillStyle = "#000";
}
const tileX = col * tileSize - camera.x;
const tileY = row * tileSize - camera.y;
ctx.fillRect(tileX, tileY, tileSize, tileSize);
}
}
// 플레이어 그리기
ctx.fillStyle = "#ff0000"; // 빨간색
ctx.fillRect(player.x - camera.x, player.y - camera.y, player.width, player.height);
}
// 메인 게임 루프
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
// 게임 시작
requestAnimationFrame(gameLoop);
</script>
</body>
</html>
코드 설명
-
HTML & CSS
<canvas> 태그를 이용해 800×600 크기의 게임 화면을 만들고, 기본 스타일로 배경색과 여백을 설정합니다.
-
타일맵 생성
map 배열에 100×100 타일을 생성합니다. 각 타일은 주로 초원(0) 타일로 지정되고, 약 10% 확률로 흙(1) 타일이 생성됩니다.
-
카메라 & 플레이어
- 플레이어는 지도 중앙에 배치되며, 키 입력에 따라 이동합니다.
- 카메라는 플레이어를 중심으로 이동하며, 지도 영역을 벗어나지 않도록 제한합니다.
-
렌더링
update() 함수에서 플레이어 및 카메라의 위치를 갱신하고,
draw() 함수에서 현재 카메라 영역 내의 타일과 플레이어를 캔버스에 그림으로써 오픈월드 느낌을 줍니다.
-
게임 루프
requestAnimationFrame을 사용해 게임 루프를 만들어 지속적으로 업데이트 및 렌더링합니다.
이 예제를 바탕으로 이미지 스프라이트, NPC, 상호작용, 전투 시스템 등 다양한 기능을 추가하면서 자신만의 도트형 RPG 오픈월드 게임을 발전시켜 보세요!