<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>class로 만들어보는 간단한 게임</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth - 100;
canvas.height = window.innerHeight - 100;
var dino = {
x: 10,
y: 200,
width: 50,
height: 50,
draw() {
ctx.fillStyle = 'green';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var img1 = new Image();
img1.src = 'cactus.png';
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);
ctx.drawImage(img1, this.x, this.y);
}
}
var cactus = new Cactus;
cactus.draw();
var timer = 0;
var cactus여러개 = [];
var 점프타이머 = 0;
function 프레임마다실행할거() {
requestAnimationFrame(프레임마다실행할거);
timer++;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (timer % 200 === 0) {
var cactus = new Cactus();
cactus여러개.push(cactus)
}
cactus여러개.forEach((a, i, o) => {
//x좌표가 0미만이면 제거
if (a.x < 0) {
o.splice(i, 1)
}
충돌하나(dino, a);
a.x--;
a.draw();
})
if (점프중 == true) {
dino.y--;
점프타이머++;
}
if (점프중 == false) {
if (dino.y < 200) {
dino.y++;
}
}
if (점프타이머 > 100) {
점프중 = false;
점프타이머 = 0
}
dino.draw();
}
var 점프중 = false;
document.addEventListener('keydown', function (e) {
if (e.code === 'Space') {
점프중 = true;
}
})
프레임마다실행할거();
//충돌확인
function 충돌하나(dino, cactus) {
var x축차이 = cactus.x - (dino.x + dino.width);
var y축차이 = cactus.y - (dino.y + dino.width);
if (x축차이 < 0 && y축차이 < 0) { //충돌시
ctx.clearRect(0, 0, canvas.width, canvas.height); //캔퍼스 클리어
cancelAnimationFrame()
}
}
</script>
</body>
</html>
추가작업
Q. 점프 하강시 점점 속도가 빨라지게?
Q. 공룡이 달리는 것처럼 보이게?
Q. 배경 다가오는건?
Q. 장애물이 나타나는 간격을 랜덤하게?
Q. 점수표기는?
#참고게임
REST API /규칙/이름짓기 (0) | 2021.10.04 |
---|---|
폼에 입력한 데이터를 서버에 전송하는 법 (POST요청) (0) | 2021.10.04 |
ES6 Promise 활용#3 Ajax 요청 성공시 또 다른곳으로 Ajax 요청 (0) | 2021.09.24 |
ES6 Promise 활용#1 <img> 이미지 로딩 성공시 특정 코드를 실행 (0) | 2021.09.24 |
ES6 Promise 사용법 (0) | 2021.09.24 |