Chrome Dinosaur Game (2)
์ด์ ๊ณต๋ฃก(dino)์ ๋ฉ์ถฐ์๊ณ ์ฌ๋ฌ ์ฅ์ ๋ฌผ(cactus)์ด ๋ค๊ฐ์ค๋ ์ํฉ๊น์ง ๊ตฌํํด๋ณด์์ต๋๋ค. ์ค๋์ ์คํ์ด์ค๋ฐ๋ฅผ ๋๋ฅด๋ฉด ๊ณต๋ฃก์ด ์ ํ๋ฅผ ํ๊ณ ๊ณต๋ฃก๊ณผ ์ฅ์ ๋ฌผ์ ์ถฉ๋ ๊ฐ์ง(Collision Detection) ๋ถ๋ถ์ ๊ตฌํํด๋ณด์์ต๋๋ค. ์ด ๋ถ๋ถ์ด ์ด๋ ค์ธ ๊ฒ์ด๋ผ๊ณ ์์ํ์๋๋ฐ ๊ฐ ๊ฐ์ฒด์ ์์น๋ง ๊ด๋ฆฌํ๋ฉด ๊ฐ๋ฅํ์๋ ๊ฒ์ด์ด์ ์๊ฐ์ธ๋ก ๋น ๋ฅด๊ฒ ์ดํดํ ์ ์์์ต๋๋ค. ์ด์ ๊ธฐ๋ณธ์ ์ธ ๊ธฐ๋ฅ ๊ตฌํ์ ๋ง์ณค์ผ๋ ์๊ฐ๋๋ ์์ด๋์ด๊ฐ ์๊ธธ ๋๋ง๋ค ๊ธฐ์กด์ ๋ง๋ค์๋ ๊ฒ์์ ์กฐ๊ธ์ฉ ์ถ๊ฐํด๋ณด๋ ค๊ตฌ์! ๋ํ ์ง๊ธ๊น์ง ๋ฐฐ์ด Java Script ๋ง์ผ๋ก๋ ๊ตฌํํ ์ ์๋ ๊ฒ๋ค์ด ๋ฌด๊ถ๋ฌด์งํ๋ค๋ ์๊ฐ์ด ๋ค์์ต๋๋ค. ์ด๋ฒ ๊ฒฝํ์ ์ด๋ ค์ ๋ค์ ๊ฒ์ ํ๋ก์ ํธ๋ ๋ชฉ์ ๋๋ก ์ ๊ตฌํํ ์ ์์์ผ๋ฉด ์ข๊ฒ ์ต๋๋ค๐๐
์ค๋ ๋ฐฐ์ ๋ ๋ด์ฉ๋ค์ ์ฝ๋ ์์ ์ฃผ์์ฒ๋ฆฌ ํ์ต๋๋ค!
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var img2 = new Image();
img2.src = 'dinosaur.png'; // make an object to place a downloaded image
var dino = {
x: 10,
y: 200,
width: 50,
height: 50,
draw() {
ctx.drawImage(img2, this.x, this.y, this.width+10, this.height+10);
}
}
var img1 = new Image();
img1.src = 'cactus.png';
class Cactus {
constructor() {
this.x = 800;
this.y = 200;
this.width = 50;
this.height = 50;
}
draw() {
ctx.drawImage(img1,this.x,this.y, this.width, this.height);
}
}
var timer = 0;
var cacti;
var animation;
var jumping = false;
var jumpTimer = 0;
function perFrame() {
animation = requestAnimationFrame(perFrame);
timer++;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(timer % 60 === 0) { // a new cactus is created every 60 frames
var cactus = new Cactus();
cacti.push(cactus);
}
cacti.forEach((a,idx,o) => { // o is the Array 'Cacti'
if (a.x < 0) {
o.splice(idx,1); // a cactus disappears after its x-value is smaller than 0
}
a.x -= 8;
collisionDetection(dino, a);
a.draw();
})
if(jumping === true) { // dino goes to the top when jumping is true
dino.y -= 5;
jumpTimer += 3;
}
if(jumping === false) {
if(dino.y < 200) {
dino.y += 5;
}
}
if (jumpTimer > 100) { // dino goes to the bottom when jumping is false
jumping = false;
}
if(dino.y === 200) {
jumpTimer = 0;
}
dino.draw();
}
perFrame();
function collisionDetection(dino, cactus) {
var xDifference = cactus.x - (dino.x + dino.width);
var yDifference = cactus.y - (dino.y + dino.height);
if(xDifference < 0 && yDifference < 0) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
cancelAnimationFrame(animation);
//This method cancels an animation request previously scheduled through a call to requestAnimationFrame
}
}
var jumping = false;
document.addEventListener('keydown', function(e) {
if(e.code === 'Space') {
jumping = true;
}
}) //When spacebar is pressed, the event listener is executed