JavaScript로 게임 만들기 - 6

Fantazindy·2022년 4월 12일
2

JSFightGame

목록 보기
6/12

이제 배경이미지를 그려볼건데 그 전에 js파일이 너무 길어 정리가 필요할 것 같다.
먼저 class를 따로 빼보자.
js폴더를 새로 만들고 classes.js파일을 새로 만든 뒤 Sprite클래스를 잘라내기 하자.
그리고 index.html안에

  <script src="js/classes.js"></script>

를 추가해주자.

정상 작동을 확인했으면 이후 작업을 시작하자.

배경을 Sprite클래스를 통해 그려줄 것이므로 기존 Sprite클래스를 한번 더 복사하고 복사한 클래스의 이름을 Fighter로 바꿔준 뒤 index.js에서 사용하고 있는 Sprite들도 Fighter로 바꿔주자

const player = new Fighter({
  position: {
    x: 0,
    y: 0,
  },
  velocity: {
    x: 0,
    y: 0,
  },
  color: "green",
  offset: {
    x: 0,
    y: 0,
  },
});

const enemy = new Fighter({
  position: {
    x: 400,
    y: 100,
  },
  velocity: {
    x: 0,
    y: 0,
  },
  color: "red",
  offset: {
    x: 50,
    y: 0,
  },
});

그리고 배경을 그려줄 때 사용할 Sprite에서 필요없는 부분을 지워주자

class Sprite {
  constructor({ position }) {
    this.position = position;
    this.width = 50;
    this.height = 150;
  }

  draw() {}

  update() {
    this.draw();
  }
}

이제 배경을 그려줄 때 필요한 것들을 추가하면 되는데 배경은 이미지를 쓸 것이기 때문에 프로퍼티로 이미지와 이미지 소스를 추가하고 constructor의 파라미터로 이미지소스를 넘겨주고 이미지, 포지션x, 포지션y를 파라미터로 받는 drawImage함수를 draw에 넣고 update에서 호출시켜주자

class Sprite {
  constructor({ position, imageSrc }) {
    this.position = position;
    this.width = 50;
    this.height = 150;
    this.image = new Image();
    this.image.src = imageSrc;
  }

  draw() {
    c.drawImage(this.image, this.position.x, this.position.y);
  }

  update() {
    this.draw();
  }
}

그리고 나서 index.js에서 이전 캐릭터들의 포지션 등 정보를 선언해주었듯이 배경에 대한 정보를 제공해주자

const background = new Sprite({
  position: {
    x: 0,
    y: 0,
  },
  imageSrc: "./img/background.png",
});

그리고 animate함수에서 캐릭터들이 그려지는 부분 이전에 background를 먼저 update되도록 하면

function animate() {
  window.requestAnimationFrame(animate);
  c.fillStyle = "black";
  c.fillRect(0, 0, canvas.width, canvas.height);
  background.update();
  player.update();
  enemy.update();
  ...


배경이 입혀진 것을 볼 수 있다.

index.js파일을 보면 아직도 코드가 많아 보기가 힘든데 좀 더 분리해보자

rectangularCollision, determineWinner 같은 기능적인 함수들을 따로 묶으면 보기 더 편할것 같다 js폴더 안에 utils.js에 옮겨주고 index.html에 스크립트를 추가해주자.

그리고 게임화면을 보면 캐릭터들이 마치 땅속에 들어가있는 느낌이 들어 어색한데 이것도 수정하자
Fighter 클래스의 update에서 canvas 높이에 딱 맞춘것에서 한 95픽셀 정도만 빼주자.

  update() {
    ...

    if (this.position.y + this.height + this.velocity.y >= canvas.height - 95) {
      ...


캐릭터의 위치가 이전보다 자연스러워졌다.

배경이미지는 마무리 된 듯 한데 아직 배경이 좀 단조로우니 다음 포스팅에선 뭔가 추가해보자

profile
풀스택 개발자를 목표로 성장중입니다!

0개의 댓글