(2-3) [JS] shooting game 만들기

씩씩한 조약돌·2023년 1월 13일
0

미니프로젝트🤹

목록 보기
5/21
post-thumbnail

참고 영상 : https://youtu.be/kfBsH4MHYUk (코딩알려주는누나)

3일차 내용

총알쏘기
1. 스페이스바를 누르면 총알 발사 (함수)
2. 스페이스바를 여러번 누르면 총알 여러개 발사 (배열)
3. 총알의 x,y좌표값 변경해주기 (x좌표는 스페이스를 누르는 시점 / 총알은 위로 올라가기 때문에 y좌표는 줄어들도록 처리)

1. setupKeyboardListener() 함수 안에 처리
스페이스바를 누르면 총알 발사 (함수)
= 스페이스바가 떼지면(keyup) / 총알생성 함수를 실행하라

  • document.addEventListener("keyup", function (event) : 스페이스바가 떼지면(keyup)
  • delete keysDown[event.keyCode]; : 조약돌의 방향을 제어
  • if (event.keyCode == 32) : 눌려진 key가 32면 (스페이스바이면)
  • createBullet();: 총알생성 함수를 실행하라
function setupKeyboardListener() {
  document.addEventListener("keydown", function (event) {
    //console.log("무슨 키가 눌렸어?", event.keyCode);

    keysDown[event.keyCode] = true;
    //console.log("KeysDown =", keysDown);
  });

  document.addEventListener("keyup", function (event) {
    delete keysDown[event.keyCode];
    //console.log("버튼 클릭 후 = ", keysDown);

    if (event.keyCode == 32) {
      //32 : spacebar
      createBullet(); //총알 생성
    }
  });
}                          

2. createBullet() 함수 생성

  • 스페이스바를 누르면 실행될 함수
function createBullet() {
  //console.log("총알 생성");
}

3. Bullet() : 총알 함수로 처리

  • 총알은 x좌표와 y좌표가 필요함
  • 여러개가 생성되어야 하기 때문에 함수로 처리함
function Bullet() {
  this.x = 0;
  this.y = 0;
}

4. createBullet() 함수 생성

  • 스페이스바를 누르면 실행될 함수
  • 총알을 생성(new)
function createBullet() {
  //console.log("총알 생성");
  
   let b = new Bullet(); // 총알 1개 생성  
}

5. Bullet() / this.init(): 총알의 좌표값 설정

  • 총알이 생성되는 위치 지정
  • 총알의 x,y 초기 좌표값은 스페이스를 누르는 시점의 조약돌 좌표값과 동일하도록 설정
function Bullet() {
  this.x = 0;
  this.y = 0;
  this.init()=function() {
    this.x = spaceshipX;
    this.y = spaceshipY;
  }
}

6. let bulletList : 생성된 총알들을 담을 배열 생성

  • let bulletList = [];
  • bulletList.push(this); : 배열에 생성된 총알들을 push
let bulletList = [];
function Bullet() {
  this.x = 0;
  this.y = 0;
  this.init()=function() {
    this.x = spaceshipX;
    this.y = spaceshipY;
    
    bulletList.push(this);
  }
}

7. createBullet() 함수 수정

  • Bullet함수의 init()함수 호출
  • 총알의 x,y좌표가 설정되고, 배열에 총알이 입력됨
function createBullet() {
  //console.log("총알 생성");
  
  let b = new Bullet(); // 총알 1개 생성
  b.init();
}

8. render() : 총알 그려주기

  • for문을 이용해 bulletList배열을 반복해서 출력
  • drawImage(이미지, x좌표, y좌표,width, height)
function render() {
  ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
  ctx.drawImage(mainImage, spaceshipX, spaceshipY, 64, 64);
  for (let i = 0; i < bulletList.length; i++) {
    ctx.drawImage(bulletImage, bulletList[i].x, bulletList[i].y, 25, 25);
  }
}

9. 중간실행

  • 총알이 조약돌의 왼쪽으로 치우쳐 나오기 때문에 x좌표값을 약간 이동해줘야함
  • 위로 쏘아올릴 수 있도록 y좌표 이동하도록 처리해야함

10. x좌표값 약간 이동시켜주기

  • this.x = spaceshipX + 20;
let bulletList = [];
function Bullet() {
  this.x = 0;
  this.y = 0;
  this.init = function () {
    this.x = spaceshipX + 20;
    this.y = spaceshipY;

    bulletList.push(this);
  };
}

11. update() : 총알 발사하도록 y좌표 수정하는 함수

  • y좌표가 -7씩 줄어들도록 처리
let bulletList = [];
function Bullet() {
  this.x = 0;
  this.y = 0;
  this.init = function () {
    this.x = spaceshipX + 20;
    this.y = spaceshipY;

    bulletList.push(this);
  };
  this.update = function () {
    this.y -= 7;
  };
}

12. update()함수에 Bullet.update()호출

  • for문으로 bulletList배열의 모든 총알들을 반복적으로 처리
  • bulletList[i]의 y값이 변경
// 우주선의 xy좌표가 바뀌고
function update() {
  if (39 in keysDown) {
    spaceshipX += 5;
  } // right

  if (37 in keysDown) {
    spaceshipX -= 5;
  } //left

  if (spaceshipX <= 0) {
    spaceshipX = 0;
  }
  if (spaceshipX >= canvas.width - 64) {
    spaceshipX = canvas.width - 64;
  }

  // 총알의 y좌표 업데이트 하는 함수
  for (let i = 0; i < bulletList.length; i++) {
    bulletList[i].update();
  }
}


3일차 전체코드

// 1. Canvas 세팅
let canvas;
let ctx;

canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 700;
document.body.appendChild(canvas);

// 2. image 가져오기
let backgroundImage, mainImage, bulletImage, enemyImage, gameOverImage;

//주인공 좌표
let spaceshipX = canvas.width / 2 - 32;
let spaceshipY = canvas.height - 64;

let bulletList = [];
function Bullet() {
  this.x = 0;
  this.y = 0;
  this.init = function () {
    this.x = spaceshipX + 20;
    this.y = spaceshipY;

    bulletList.push(this);
  };
  this.update = function () {
    this.y -= 7;
  };
}

function loadImage() {
  backgroundImage = new Image();
  backgroundImage.src = "images/background.jpg";

  mainImage = new Image();
  mainImage.src = "images/main.png";

  bulletImage = new Image();
  bulletImage.src = "images/bullet.png";

  enemyImage = new Image();
  enemyImage.src = "images/enemy.png";

  gameOverImage = new Image();
  gameOverImage.src = "images/gameover.jpg";
}

//방향키 누르면
let keysDown = {};
function setupKeyboardListener() {
  document.addEventListener("keydown", function (event) {
    //console.log("무슨 키가 눌렸어?", event.keyCode);

    keysDown[event.keyCode] = true;
    //console.log("KeysDown =", keysDown);
  });

  document.addEventListener("keyup", function (event) {
    delete keysDown[event.keyCode];
    //console.log("버튼 클릭 후 = ", keysDown);

    if (event.keyCode == 32) {
      //32 : spacebar
      createBullet(); //총알 생성
    }
  });
}

function createBullet() {
  //console.log("총알 생성");
  let b = new Bullet(); // 총알 1개 생성
  b.init();
  console.log("총알 리스트 : ", bulletList);
}

// 우주선의 xy좌표가 바뀌고
function update() {
  if (39 in keysDown) {
    spaceshipX += 5;
  } // right

  if (37 in keysDown) {
    spaceshipX -= 5;
  } //left

  if (spaceshipX <= 0) {
    spaceshipX = 0;
  }
  if (spaceshipX >= canvas.width - 64) {
    spaceshipX = canvas.width - 64;
  }

  // 총알의 y좌표 업데이트 하는 함수
  for (let i = 0; i < bulletList.length; i++) {
    bulletList[i].update();
  }
}

function render() {
  ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
  ctx.drawImage(mainImage, spaceshipX, spaceshipY, 64, 64);
  for (let i = 0; i < bulletList.length; i++) {
    ctx.drawImage(bulletImage, bulletList[i].x, bulletList[i].y, 25, 25);
  }
}

function main() {
  update(); // 좌표값 업데이트
  render(); //그려주기
  requestAnimationFrame(main);
  //console.log("anmiation calls");
}

loadImage();
setupKeyboardListener();
main();

3일차 후기

1. 함수 하나에 한가지 기능만 넣어줘야함

profile
씩씩하게 공부중 (22.11~)

0개의 댓글