[고민] 점프 후 물체가 다시 제자리로 오는 방법

2021. 9. 13. 21:10알고리즘 고민

반응형
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

canvas.width = window.innerWidth - 100;
canvas.height = window.innerHeight - 100;

// 코드를 입력하면 네모(🔲)가 생성이 된다.

const dino = {
  x: 10,
  y: 200,
  width: 50,
  height: 50,
  draw() {
    ctx.fillStyle = "green";
    ctx.fillRect(this.x, this.y, this.width, this.height);
  },
};

class Cactus {
  constructor() {
    this.x = 500;
    this.y = 200;
    this.width = 50;
    this.height = 50;
  }

  draw() {
    ctx.fillStyle = "red";
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}

let timer = 0;
let cactuss = [];
let isJumping = false;
let jumpTimer = 0;

function frameAction() {
  requestAnimationFrame(frameAction);
  timer++;
  const cactus = new Cactus();

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  if (timer % 120 === 0) {
    cactuss.push(cactus);
    cactus.draw();
  }

  cactuss.forEach((a, i, o) => {
    a.x--;
    if (a.x < 0) {
      o.splice(i, 1);
    }

    a.draw();
  });

  if (isJumping === true) {
    dino.y--;
    jumpTimer++;
  }
  if (jumpTimer > 100) {
    isJumping = false;
  }
  // 🤔 : 물체가 점프를 한 후, 어떻게 다시 제 자리로 오게 할 것인가?
  //      여기 라인에서 작성...

  dino.draw();
}

frameAction();

document.addEventListener("keypress", (e) => {
  if (e.code === "Space") {
    isJumping = true;
  }
});

 

JS로 만드는 슈퍼마리오 웹 게임이다.

현재 물체가 점프까지를 했지만, 다시 제자리로 오려면 어떻게 해야 하는지 고민이 되는 상황이고,

이를 2일째 고민 중이다.

이후 이걸 고민 한 후 해결 하면 [해결] 테마에 기록을 남길 것이다. 

화면 기록 2021-09-13 오후 9.08.36.mov
0.28MB

반응형