zoaseo
To Infinity And Beyond
zoaseo
전체 방문자
오늘
어제
  • 분류 전체보기 (763)
    • 개발이 좋아서 (381)
      • SAP가 좋아서 (3)
      • Java가 좋아서 (42)
      • Spring이 좋아서 (50)
      • JPA가 좋아서 (0)
      • QueryDSL이 좋아서 (26)
      • Docker가 좋아서 (7)
      • Redis가 좋아서 (7)
      • AWS가 좋아서 (5)
      • CI/CD가 좋아서 (6)
      • Troubleshooting이 좋아서 (4)
      • Kotlin이 좋아서 (7)
      • SQL이 좋아서 (6)
      • HTTP가 좋아서 (21)
      • JavaScript가 좋아서 (30)
      • TypeScript가 좋아서 (6)
      • Vue가 좋아서 (21)
      • Flutter가 좋아서 (61)
      • React가 좋아서 (20)
      • Redux(React)가 좋아서 (2)
      • Angular가 좋아서 (22)
      • HTML이 좋아서 (9)
      • CSS가 좋아서 (15)
      • PHP가 좋아서 (9)
      • Illustrator가 좋아서 (2)
    • 노력이 좋아서 (169)
    • 결과물이 좋아서 (14)
    • 코딩연습이 좋아서 (168)
      • 이론이 좋아서 (62)
      • SQL이 좋아서 (90)
    • 유용한 사이트가 좋아서 (28)
    • Github (2)

인기 글

티스토리

hELLO · Designed By 정상우.
zoaseo

To Infinity And Beyond

<step62>'js_canvas_jumpGame'
노력이 좋아서

<step62>'js_canvas_jumpGame'

2022. 6. 17. 11:12

1) 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>
    <style>
        canvas {
            background: url(./img/back.jpg) center left/90% no-repeat;
        }
    </style>
</head>
<body>
    <canvas></canvas>
    <img style="display:none;" src="/canvas/jumpGame/img/pig.png" alt="">
    <img style="display:none;" src="/canvas/jumpGame/img/dinoo.png" alt="">
    <script>
        //점프 게임
        //사각형을 그림
        //점프 기능
        //충돌 체크
        let canvas = document.querySelector('canvas');
        let ctx = canvas.getContext('2d');

        canvas.width = window.innerWidth - 350;
        canvas.height = window.innerHeight - 500;

        let imgElem2 = new Image();
        imgElem2.src = '/canvas/jumpGame/img/alen.png';

        let obsImgs = document.querySelectorAll('img');

        //변수정의
        let animation;
        let timer = 0;
        let jump = false;
        let jumptimer = 0;

        //주인공 객체 만들기
        let gameU = {
            x: 30,
            y: 300,
            width: 50,
            height: 50,
            draw(){
                ctx.drawImage(imgElem2,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;
                //num은 0,1,2 랜덤값이 지정
                this.num = Math.floor(Math.random()*2);
            }
            draw(){
                ctx.drawImage(obsImgs[this.num],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>

'노력이 좋아서' 카테고리의 다른 글

<step63>'js_wave'  (0) 2022.06.20
<step62>'js_canvas_module'  (0) 2022.06.17
<step61>'js_canvas'  (0) 2022.06.16
<step60>'js_fetch_shoppinglist'  (0) 2022.06.15
<step60>'js_비동기처리'  (0) 2022.06.15

    티스토리툴바