엘리스 AI트랙 1차 스터디 4주차

Deong_gu·2022년 7월 27일
0
post-thumbnail

[엘리스 AI트랙 5기 1차 스터디 프로젝트]

<canvas 요소와 JavaScript를 활용해서 벽돌 부수기 게임 만들기>

1. 서론

3주차 문제는 해결되지 못하고, 어느 정도의 결과물을 내야된다는 생각에 다른 부분을 진행시켰다. 벽돌 부수기의 핵심! 공, 공의 움직임 구현이다.

2. 본론

3주차에 배웠던 clearRect 메서드를 활용해서 이번에는 좌우로만 움직이는 막대기가 아니라 공의 상하좌우의 움직임을 구현해야한다.
공을 그리고, 공의 좌표를 조절하고, 이전 공의 위치를 지우고, 벽에 충돌했을때 더해지는 좌표의 부호를 바꾸고, 막대기와 충돌 구현

3. 결론

x, y 좌표에 고정된 값을 더해주면서 움직임을 구현하다보니까 정해진 각도, 정해진 움직임으로 한계를 보였다. 함수 호출 순서에 따라서 테두리가 지워지거나 겹쳐지는 문제가 생기는데, 해결할 수 있을까... 일단 넘어가야겠다.

// 공
const ball = {
  x: 200,
  y: 335,
  vx: 5,
  vy: 2,
  radius: 15,
  color: "black",
};


function drawBall() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.fillStyle = ball.color;
  ctx.fill();
}


//충돌
function collisionDetection() {
  if (
    ball.y + ball.vy + ball.radius > bar.y &&
    ball.y + ball.vy + ball.radius < bar.y + bar.height &&
    ball.x >= bar.x &&
    ball.x <= bar.x + bar.width
  ) {
    ctx.beginPath();
    ctx.arc(
      ball.x - ball.radius - ball.vx,
      ball.y - ball.radius - ball.vy,
      ball.radius,
      0,
      true
    );
    ctx.closePath();
    ctx.fillStyle = "black";
    ctx.fill();

    ball.vy = -ball.vy;
    ball.vx = -ball.vx;
    ball.x += ball.vx;
    ball.y += ball.vy;

    window.requestAnimationFrame(draw);
  } else {
    ball.x += ball.vx;
    ball.y += ball.vy;

    window.requestAnimationFrame(draw);
  }

  if (
    ball.x + ball.vx > canvas.width - ball.radius ||
    ball.x + ball.vx < ball.radius
  ) {
    ball.vx = -ball.vx;
  }

  //천장 충돌
  if (ball.y + ball.vy < ball.radius) {
    ball.vy = -ball.vy;
  }
}

function draw() {
  drawBall();
  collisionDetection();
}

drawBall();

profile
프론트엔드 개발자가 되기 위해 공부 중입니다.

0개의 댓글