Stack/JavaScript
[JS] JumpGame
7ingout
2022. 6. 17. 16:01
mgame.html
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
body {
display: flex;
justify-content: center;
}
canvas {
background: url('img/헤네풀숲.png') center center/90% no-repeat;
}
</style>
</head>
<body>
<canvas></canvas>
<img style="display: none;" src="img/버섯.png" alt="">
<img style="display: none;" src="img/슬라임.png" alt="">
<img style="display: none;" src="img/돼지.png" alt="">
<script>
// 점프게임
// 사각형을 그림
// 점프기능
// 충돌체크
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
canvas.width = window.innerWidth - 200;
canvas.height = window.innerHeight - 200;
// 변수정의
let animation;
let timer = 0;
let jump = false;
let jumptimer = 0;
let catIme = new Image();
catIme.src = "img/character.png";
// 장애물 이미지 노드리스트
let obsImgs = document.querySelectorAll('img');
// 주인공객체 만들기
let gameU = {
x: 350,
y: 400,
width: 135,
height: 125,
draw() {
// ctx.fillStyle = "green";
// ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.drawImage(catIme, this.x, this.y, this.width, this.height);
}
}
gameU.draw();
// 장애물 배열
let obstacleArr = [];
// 장애물 만들기
class Obstacle {
constructor() {
this.x = 1400;
this.y = 400;
this.width = 135,
this.height = 125,
// num은 0, 1, 2 랜덤값이 지정
this.num = Math.floor(Math.random()*3);
}
draw() {
ctx.drawImage(obsImgs[this.num], this.x, this.y, this.width, this.height);
// ctx.fillStyle = "red";
// ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
// 화면을 계속해서 진행하는 함수
// 애니메이션 만들기
// 1초에 60번 실행함
// 장애물은 2~3초 하나씩 생성
function startFrame() {
animation = requestAnimationFrame(startFrame);
timer ++;
// 캔버스 지우기
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
// timer가 180증가 될 때마다 장애물을 생성
// 장애물 배열에 넣기
if(timer % 180 === 0 ) {
let obs = new Obstacle;
obstacleArr.push(obs);
}
obstacleArr.forEach((item, index, arr) => {
// 왼쪽으로 이동된 장애물 제거하기
// x좌표가 0보다 작으면 배열에서 제거
if(item.x < 180) {
arr.splice(index, 1);
}
item.x -= 5;
item.draw();
// 충돌하는지 확인
crashCheck(gameU, item);
})
// 스페이스 눌렀을 때 올라갔다가 내려오기
if(jump) {
gameU.y -=3 ;
jumptimer += 1;
} else {
if(gameU.y < 400) gameU.y +=3 ;
}
if(jumptimer > 50) {
jump = false;
jumptimer = 0;
}
gameU.draw();
}
startFrame();
// 키 이벤트
window.addEventListener("keydown", function(e) {
if(e.code == "Space") {
jump = true;
console.log(jump);
}
})
// 충돌 확인하기
function crashCheck(user, item) {
let x차이 = item.x - (user.x + user.width);
let y차이 = item.y - (user.y);
console.log(`y차이::::::::: ${y차이}`)
if(x차이<= 0 && y차이 <= 0) {
cancelAnimationFrame(animation);
console.log(`xx${x차이}`);
console.log(`yy${y차이}`);
console.log("충돌");
}
}
</script>
</body>
</html>
game.html
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<canvas></canvas>
<script>
// 점프게임
// 사각형을 그림
// 점프기능
// 충돌체크
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
canvas.width = window.innerWidth - 200;
canvas.height = window.innerHeight - 200;
// 변수정의
let animation;
let timer = 0;
let jump = false;
let jumptimer = 0;
// 주인공객체 만들기
let gameU = {
x: 30,
y: 300,
width: 50,
height: 50,
draw() {
ctx.fillStyle = "green";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
gameU.draw();
// 장애물 배열
let obstacleArr = [];
// 장애물 만들기
class Obstacle {
constructor() {
this.x = 900;
this.y = 300;
this.width = 50;
this.height = 50;
}
draw() {
ctx.fillStyle = "red";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
// 화면을 계속해서 진행하는 함수
// 애니메이션 만들기
// 1초에 60번 실행함
// 장애물은 2~3초 하나씩 생성
function startFrame() {
animation = requestAnimationFrame(startFrame);
timer ++;
// 캔버스 지우기
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
// timer가 180증가 될 때마다 장애물을 생성
// 장애물 배열에 넣기
if(timer % 180 === 0 ) {
let obs = new Obstacle;
obstacleArr.push(obs);
}
obstacleArr.forEach((item, index, arr) => {
// 왼쪽으로 이동된 장애물 제거하기
// x좌표가 0보다 작으면 배열에서 제거
if(item.x < 0) {
arr.splice(index, 1);
}
item.x--;
item.draw();
// 충돌하는지 확인
crashCheck(gameU, item);
})
// 스페이스 눌렀을 때 올라갔다가 내려오기
if(jump) {
gameU.y--;
jumptimer++;
} else {
if(gameU.y < 300) gameU.y++;
}
if(jumptimer > 100) {
jump = false;
jumptimer = 0;
}
gameU.draw();
}
startFrame();
// 키 이벤트
window.addEventListener("keydown", function(e) {
if(e.code == "Space") {
jump = true;
console.log(jump);
}
})
// 충돌 확인하기
function crashCheck(user, item) {
let x차이 = item.x- (user.x+user.width);
let y차이 = item.y- (user.y+user.height/2);
if(x차이 <= 0 && y차이 <= 0) {
cancelAnimationFrame(animation);
console.log("충돌");
}
}
</script>
</body>
</html>