타워 디펜스 프로젝트 - 데이터 로딩 문제

ssini·2024년 12월 30일
0

오늘은 팀 프로젝트로 진행 중인 타워 디펜스 게임에서 데이터 로딩 타이밍 문제를 발견하고 해결한 과정을 기록한다. 서버로부터 사용자 데이터를 받아오기 전에 게임 초기화가 실행되어 gameUserDatanull로 출력되는 문제가 발생했다.

문제 상황

  • socket.js에서 connection 이벤트가 발생하며 서버로부터 userData를 받아오는 로직이 있었다.
  • 하지만 game.js에서 initGame 함수가 데이터 로딩이 끝나기 전에 호출되어 gameUserDatanull로 출력되는 문제가 있었다.

기존 코드 흐름

  1. socket.js에서 서버로부터 데이터를 받는 로직:
socket.on('connection', (data) => {
  console.log('connection: ', data);
  
  if (data.userData) {
    gameData.userData = data.userData;
  }
});

export const getUserData = () => gameData.userData;
  1. game.js에서 이미지 로딩 후 바로 initGame을 호출:
if (!isInitGame) {
  initGame();

  const gameUserData = getUserData();
  console.log('gameUserData: ', gameUserData); // 이 부분에서 null 출력
}

해결 방법

1. socket.js 수정

  • connection 이벤트에서 userData를 받은 후 initGame을 호출하도록 수정하고, initGameuserData를 전달했다.
socket.on('connection', (data) => {
  console.log('connection: ', data);

  if (data.userData) {
    if (!isInitGame) {
      initGame(data.userData);
    }
  }
});

2. game.js 수정

  • initGame 함수가 socket.js에서 호출될 수 있도록 export했다.
export async function initGame(receivedUserData) {
  if (isInitGame || !receivedUserData) {
    return;
  }

  userData = receivedUserData;
  console.log('gameUserData: ', userData); // null이 아닌 데이터 출력

  isInitGame = true;
  // ... 추가 초기화 코드
}

해결 결과

  1. 서버로부터 userData를 받은 후에만 게임이 초기화되도록 수정했다.
  2. gameUserDatanull이 아닌 서버에서 받은 데이터를 가지게 되었다.
  3. 데이터 로딩 순서가 보장되면서 게임 실행의 안정성이 높아졌다.

0개의 댓글

관련 채용 정보