웹 프론트엔드 H5 튜토리얼 HTML5 Canvas를 사용하여 간단한 자위 게임 만들기 game_html5 튜토리얼 기술

HTML5 Canvas를 사용하여 간단한 자위 게임 만들기 game_html5 튜토리얼 기술

May 16, 2016 pm 03:46 PM
canvas html5

이전에 Donnet의 DEMO에서 자위 게임을 본 후 해당 게임의 사진과 오디오를 삭제했습니다. . . . 그냥 재미로 다시 썼습니다. 단지 오락을 위해서입니다. . . . . . 저는 프레임워크를 사용하지 않고 모든 js를 직접 작성합니다. . . . . . 그래서 이것은 캔버스를 처음 접하는 사람들에게 도움이 될 수 있습니다. 작가는 오랫동안 캔버스를 연주하지 않았으며 실력이 좋지 않습니다.

더 이상 고민하지 말고 먼저 DEMO: 비행기 게임부터 시작하겠습니다. 원본 포스터는 단지 재미로 쓴 것이지 진지한 게임에 쓸 의도는 없었습니다.

본론으로 들어가 보겠습니다. 자위 게임 파일에는 index.html 항목 파일, allSprite.js 스프라이트의 논리 처리 파일, loading.js 로딩 처리 파일 및 data.js(일부 초기화된 데이터)가 포함되어 있습니다.

우선 일반 게임은 기본적으로 로딩이 필요합니다. 로딩 페이지는 스프라이트 시트 이미지, 오디오 등의 데이터를 미리 로드하는 데 사용됩니다. 이 게임은 작은 게임이므로 일부 오디오와 이미지만 로드하면 됩니다. 안에 있는 로딩 코드는 주로 다음과 같습니다. 다른 것들은 로딩 애니메이션을 만들기 위한 것입니다. 관심이 있으시면 게시하지 않겠습니다.

XML/HTML 코드클립보드에 콘텐츠 복사
  1. loadImg:함수(데이터){   
  2.             var _this = this;   
  3.             var dataIndex = 0;   
  4.             li();   
  5.             함수 li(){   
  6.                if(datas[dataIndex].indexOf("mp3")>=0){   
  7.                    var 오디오 = 문서.createElement("audio");   
  8.                    document.body.appendChild(audio);   
  9.                    audio.preload = "auto";   
  10.                    audio.src = 데이터[dataIndex];   
  11.                    audio.oncanplaythrough = 기능(){   
  12.                       this.oncanplaythrough = null;   
  13.                        dataIndex ;   
  14.                        if(dataIndex===datas.length){   
  15.                            _this.percent = 100;   
  16.                        }그렇지 않으면 {   
  17.                            _this.percent = parseInt(dataIndex/datas.length*100);   
  18.                            li.call(_this);   
  19.                        }   
  20.                    }   
  21.                 }그렇지 않으면 {   
  22.                    preLoadImg(datas[dataIndex] , function(){   
  23.                        dataIndex ;   
  24.                        if(dataIndex===datas.length){   
  25.                            _this.percent = 100;   
  26.                       } 그 외 {   
  27.                            _this.percent = parseInt(dataIndex/datas.length*100);   
  28.                            li.call(_this);   
  29.                        }   
  30.                    })   
  31.                 }   
  32.             }   
  33.         },   
  34.   
  35. //再贴出preLoadImg적 방법   
  36. preLoadImg(src, 콜백) 함수{   
  37.     var img = new 이미지();   
  38.     img.src = src;   
  39.     if(img.complete){   
  40.         callback.call(img);   
  41.     }else {   
  42.         img.onload = 기능(){   
  43.            callback.call(img);   
  44.         }   
  45.     }   
  46. }     


먼저 배열을 사용하여 파일에 대한 링크를 data.js에 저장한 다음 이 링크가 사진인지 오디오인지 확인합니다. 사진인 경우 preLoadImg를 사용하여 사진을 미리 로드합니다. 매우 간단합니다. 새 그림을 만든 다음 여기에 링크를 할당하고 로드한 후 다시 호출하면 됩니다. 오디오는 HTML5 오디오 DOM 개체를 생성하고 이에 대한 링크를 할당하여 로드됩니다. 오디오에는 "canplaythrough" 이벤트가 있습니다. 브라우저가 버퍼링을 위해 중지하지 않고 지정된 오디오/비디오를 계속 재생할 수 있을 것으로 예상하면 canplaythrough 이벤트가 발생합니다. , 이는 canplaythrough가 호출되면 오디오가 거의 로드되었으며 다음 오디오를 로드할 수 있음을 의미합니다. 이와 같이 모든 것이 로드된 후 콜백이 이루어지고 게임이 시작됩니다.

게임이 시작되면 여러 개체가 필요하므로 이를 하나의 스프라이트 개체로 통합했습니다. 서로 다른 개체 간의 각 프레임 이동은 동작을 사용하여 별도로 작성할 수 있습니다.

XML/HTML 코드클립보드에 콘텐츠 복사
  1. W.Sprite = 함수(이름 , 페인터 , 행동 , 인수){   
  2.     if(이름 !== 정의되지 않음) this.name = 이름;   
  3.     if(painter !== undefine) this.painter = painter;   
  4.     this.top = 0;   
  5.     this.left = 0;   
  6.     this.width = 0;   
  7.     this.height = 0;   
  8.     this.velocityX = 3;   
  9.     this.velocityY = 2;   
  10.     this.visible = true;   
  11.     this.animating = 거짓;   
  12.     this.behaviors = 행동;   
  13.     this.rotateAngle = 0;   
  14.     this.blood = 50;   
  15.     this.fullBlood = 50;   
  16.     if(이름==="계획"){   
  17.         this.rotateSpeed = 0.05;   
  18.         this.rotateLeft = false;   
  19.         this.rotateRight = 거짓;   
  20.         this.fire = false;   
  21.         this.firePerFrame = 10;   
  22.         this.fireLevel = 1;   
  23.     }else if(이름==="별"){   
  24.         this.width = 수학.random()*2;   
  25.         this.speed = 1*this.width/2;   
  26.         this.lightLength = 5;   
  27.         this.cacheCanvas = document.createElement("canvas");   
  28.         thisthis.cacheCtx = this.cacheCanvas.getContext('2d');   
  29.         thisthis.cacheCanvas.width = this.width this.lightLength*2;   
  30.         thisthis.cacheCanvas.height = this.width this.lightLength*2;   
  31.         this.painter.cache(this);   
  32.     }else if(이름==="badPlan"){   
  33.         this.badKind = 1;   
  34.         this.speed = 2;   
  35.         this.rotateAngle = 수학.PI;   
  36.     }else if(이름==="missle"){   
  37.         this.width = missleWidth;   
  38.     }else if(이름==="boom"){   
  39.         this.width = boomWidth;   
  40.     }else if(이름==="food"){   
  41.         this.width = 40;   
  42.         this.speed = 3;   
  43.         this.kind = "레벨UP"  
  44.     }  
  45.     this.toLeft = false;   
  46.     this.toTop = false;   
  47.     this.toRight = false;   
  48.     this.toBottom = false;   
  49.   
  50.     this.outArcRadius = 수학.sqrt((this.width/2*this.width/2 )*2);   
  51.   
  52.     if(args){   
  53.         for(var arg in args){   
  54.             this[arg] = args[arg];   
  55.         }   
  56.     }   
  57. }   
  58. Sprite.prototype = {   
  59.     생성자:Sprite,   
  60.     paint:function(){   
  61.         if(this.name==="badPlan"){this.update();}   
  62.   
  63.         if(this.painter !== 정의되지 않음 && this.visible){   
  64.             if(this.name!=="badPlan") {   
  65.                 this.update();   
  66.             }   
  67.             if(this.name==="plan"||this.name===" missle"||this.name==="badPlan"){   
  68.                 ctx.save();   
  69.                 ctx.translate(this.left , this.top);   
  70.                 ctx.rotate(this.rotateAngle);   
  71.                 this.painter.paint(this);   
  72.                 ctx.restore();   
  73.             }그렇지 않으면 {   
  74.                 this.painter.paint(this);   
  75.             }   
  76.         }   
  77.     },
  78. 업데이트:기능(시간){
  79. if(this.behaviors){
  80. for(var i=0;i<this.behaviors.length;i ){
  81. this.behaviors[i].execute(this,time)
  82.                                                         
  83.                                                        
  84. }
  85. }
Elf 클래스를 작성한 후 각 페인터와 동작을 작성하여 다양한 객체를 생성할 수 있습니다. 다음 단계는 페인터 작성입니다. 페인터는 일반 페인터와 스프라이트 시트 페인터 두 가지로 나누어집니다. 폭발 애니메이션과 비행기 사격 애니메이션은 그림 하나로는 할 수 없기 때문에 사용해야 할 때입니다. 스프라이트 시트로:



2015511181456172.png (168×24)

이를 그리려면 스프라이트 시트 페인터를 사용자 정의해야 합니다. 다음은 게임의 복잡성에 따라 적절할 때까지 스프라이트 시트 작성 방법을 수정할 수 있습니다. , 원칙은 유사합니다. 즉, 약간만 수정했습니다.

2015511181533636.png (896×64)

XML/HTML 코드

클립보드에 콘텐츠 복사
  1. var SpriteSheetPainter = 함수(셀){   
  2.             this.cells = 셀 || [];   
  3.             this.cellIndex = 0;   
  4.         }   
  5.         SpriteSheetPainter.prototype = {   
  6.             advanced:function(){   
  7.                if(this.cellIndex === this.cells.length-1){   
  8.                    this.cellIndex = 0;   
  9.                 }   
  10.                 else this.cellIndex ;   
  11.             },   
  12.             페인트:기능(스프라이트){   
  13.                var cell = this.cells[this.cellIndex];   
  14.                context.drawImage(spritesheet , cell.x , cell.y , cell.w , cell.h , sprite.left , sprite.top , cell.w , cell.h);   
  15.             }   
  16.         }     

而普는 일반적인 그림 제조 업체, 直接写一个화가, 把要画的什么东西tour写进去就行了.

<… >


JavaScript 코드
复复内容到剪贴板
  1. (기능(W){   
  2.     "엄격한 사용"  
  3.     var planWidth = 24,   
  4.         planHeight = 24,   
  5.         missleWidth = 70,   
  6.         missleHeight = 70,   
  7.         boomWidth = 60;   
  8.     //精灵类   
  9.     W.Sprite = 함수(이름 , 페인터 , 행동 , 인수){   
  10.         if(name !== undefine) this.name = name;   
  11.         if(painter !== undefine) this.painter = painter;   
  12.         이것.top = 0;   
  13.         이것.left = 0;   
  14.         이것.width = 0;   
  15.         이것.height = 0;   
  16.         이것.velocityX = 3;   
  17.         이것.velocityY = 2;   
  18.         이것.visible = true;   
  19.         이것.animating = false;   
  20.         이것.behaviors = behaviors;   
  21.         이것.rotateAngle = 0;   
  22.         이것.blood = 50;   
  23.         이것.fullBlood = 50;   
  24.         if(name==="계획"){   
  25.             이것.rotateSpeed = 0.05;   
  26.             이것.rotateLeft = false;   
  27.             이것.rotateRight = false;   
  28.             이것.fire = false;   
  29.             이것.firePerFrame = 10;   
  30.             이것.fireLevel = 1;   
  31.         }else if(name==="별" ){   
  32.             이것.width = Math.random()*2;   
  33.            이것.speed = 1*이것.width/2;   
  34.             이것.lightLength = 5;   
  35.            이것.cacheCanvas = document.createElement("canvas");   
  36.            이것.cacheCtx = 이것.cacheCanvas.getContext('2d');   
  37.            이것.cacheCanvas.width = 이것.width 이것.lightLength*2;   
  38.            이것.cacheCanvas.height = 이것.width 이것.lightLength*2;   
  39.             이것.painter.cache(이것);   
  40.         }else if(name==="badPlan" ){   
  41.             이것.badKind = 1;   
  42.             이것.speed = 2;   
  43.             이것.rotateAngle = Math.PI;   
  44.         }else if(name==="missle" ){   
  45.             이것.width = missleWidth;   
  46.         }else if(name==="boom" ){   
  47.             이것.width = boomWidth;   
  48.         }else if(name==="음식"){   
  49.             이것.width = 40;   
  50.             이것.speed = 3;   
  51.            이것.kind = "레벨UP"  
  52.         }   
  53.         이것.toLeft = false;   
  54.         이것.toTop = false;   
  55.         이것.toRight = false;   
  56.         이것.toBottom = false;   
  57.   
  58.         이것.outArcRadius = Math.sqrt((이것.width/2*이것.width/2)*2);   
  59.   
  60.         if(args){   
  61.            for(var arg  args){
  62.                이것[arg] = args[arg];   
  63.             }   
  64.         }   
  65.     }   
  66.     Sprite.prototype = {   
  67.         생성자:Sprite,   
  68.         페인트:기능(){   
  69.            if(.name==="나쁜 계획" ){이것.update();}   
  70.   
  71.            if(this.painter !== undefine && this .visible){   
  72.                if(.name!=="badPlan" ) {   
  73.                    이것.update();   
  74.                 }  
  75.                만약(이것.name==="계획" ||이것.name==="미스"||이것 .name==="나쁜 계획"){   
  76.                    ctx.save();   
  77.                    ctx.translate(this.left , this.top);   
  78.                    ctx.rotate(this.rotateAngle);   
  79.                    이것.painter.paint(이것);   
  80.                    ctx.restore();   
  81.                }그 외 {   
  82.                    이것.painter.paint(이것);   
  83.                 }   
  84.             }   
  85.         },   
  86.         업데이트:기능(시간){   
  87.            if(this.behaviors){   
  88.                for(var i=0;i<이것.behaviors.length;i ){   
  89.                    이것.behaviors[i].execute(이것,time);   
  90.                 }   
  91.             }   
  92.         }   
  93.     }  
  94.   
  95.     // 精灵表绘器   
  96.     W.SpriteSheetPainter = 함수(cells , isloop , endCallback , spritesheet){   
  97.         이것.cells = cells || [];   
  98.         이것.cellIndex = 0;   
  99.         이것.dateCount = null;   
  100.         이것.isloop = isloop;   
  101.         이것.endCallback = endCallback;   
  102.         이것.spritesheet = spritesheet;   
  103.     }   
  104.     SpriteSheetPainter.prototype = {   
  105.         고급:기능(){   
  106.            이것.cellIndex = 이것.isloop?(이것.cellIndex===.cells.length-1?0:.cellIndex 1):(.cellIndex 1);   
  107.         },   
  108.         페인트:기능(스프라이트){   
  109.            if(.dateCount===null){   
  110.                이것.dateCount = new Date();   
  111.             }그밖에 {   
  112.                var newd = new Date();   
  113.                var tc = newd-this.dateCount;   
  114.                (tc>40){   
  115.                    이것.advance();   
  116.                    이것.dateCount = newd;   
  117.                 }   
  118.             }  
  119.            if(이것.cellIndex<이것. cells.length ||  .isloop){   
  120.                var cell = this.cells[this .cellIndex];   
  121.                ctx.drawImage(this.spritesheet , cell.x , cell.y , cell.w , cell.h , sprite.left-sprite.width/ 2, sprite.top-sprite.width/2, cell.w, cell.h);   
  122.             } else if(this.endCallback) {   
  123.                이것.endCallback.call(sprite);   
  124.                이것.cellIndex = 0;   
  125.             }   
  126.         }   
  127.     }   
  128.   
  129.     //특제제폐제   
  130.     W.controllSpriteSheetPainter = 함수(셀 , 스프라이트 시트){   
  131.         이것.cells = cells || [];   
  132.         이것.cellIndex = 0;   
  133.         이것.dateCount = null;   
  134.         이것.isActive = false;   
  135.         이것.derection = true;   
  136.         이것.spritesheet = spritesheet;   
  137.     }  
  138.     controllSpriteSheetPainter.prototype = {   
  139.         고급:기능(){   
  140.            if(this.isActive){   
  141.                 이것.cellIndex ;   
  142.                if(이것.cellIndex === 이것.cells.length){   
  143.                    이것.cellIndex = 0;   
  144.                    이것.isActive = false;   
  145.                 }   
  146.             }   
  147.         },   
  148.         페인트:기능(스프라이트){   
  149.            if(.dateCount===null){   
  150.                이것.dateCount = new Date();   
  151.             }그밖에 {   
  152.                var newd = new Date();   
  153.                var tc = newd-this.dateCount;   
  154.                (tc>sprite.firePerFrame){   
  155.                    이것.advance();   
  156.                    이것.dateCount = newd;   
  157.                 }   
  158.             }   
  159.            var cell = this.cells[this .cellIndex];   
  160.            ctx.drawImage(this.spritesheet , cell.x , cell.y , cell.w , cell.h , -planWidth/2 , -planHeight/ 2, cell.w, cell.h);   
  161.         }  
  162.     }   
  163.   
  164.     W.planBehavior = [   
  165.         {실행:함수(스프라이트,시간){   
  166.             if(sprite.toTop){   
  167.                 sprite.top = sprite.top
  168.             }   
  169.             if(sprite.toLeft){   
  170.                 sprite.left = sprite.left
  171.             }   
  172.             if(sprite.toRight){   
  173.                 sprite.left = sprite.left>canvas.width-planWidth/2? sprite.left : sprite.left sprite.velocityX;   
  174.             }   
  175.             if(sprite.toBottom){   
  176.                 sprite.top = sprite.top>canvas.height-planHeight/2? sprite.top : sprite.top sprite.velocityY;   
  177.             }   
  178.             if(sprite.rotateLeft){   
  179.                 sprite.rotateAngle -= sprite.rotateSpeed;   
  180.             }   
  181.            if(sprite.rotateRight){   
  182.                 sprite.rotateAngle  = sprite.rotateSpeed;   
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

HTML의 테이블 테두리 HTML의 테이블 테두리 Sep 04, 2024 pm 04:49 PM

HTML의 테이블 테두리 안내. 여기에서는 HTML의 테이블 테두리 예제를 사용하여 테이블 테두리를 정의하는 여러 가지 방법을 논의합니다.

HTML 여백-왼쪽 HTML 여백-왼쪽 Sep 04, 2024 pm 04:48 PM

HTML 여백-왼쪽 안내. 여기에서는 HTML margin-left에 대한 간략한 개요와 코드 구현과 함께 예제를 논의합니다.

HTML의 중첩 테이블 HTML의 중첩 테이블 Sep 04, 2024 pm 04:49 PM

HTML의 Nested Table에 대한 안내입니다. 여기에서는 각 예와 함께 테이블 내에 테이블을 만드는 방법을 설명합니다.

HTML 테이블 레이아웃 HTML 테이블 레이아웃 Sep 04, 2024 pm 04:54 PM

HTML 테이블 레이아웃 안내. 여기에서는 HTML 테이블 레이아웃의 값에 대해 예제 및 출력 n 세부 사항과 함께 논의합니다.

HTML 입력 자리 표시자 HTML 입력 자리 표시자 Sep 04, 2024 pm 04:54 PM

HTML 입력 자리 표시자 안내. 여기서는 코드 및 출력과 함께 HTML 입력 자리 표시자의 예를 논의합니다.

HTML에서 텍스트 이동 HTML에서 텍스트 이동 Sep 04, 2024 pm 04:45 PM

HTML에서 텍스트 이동 안내. 여기서는 Marquee 태그가 구문과 함께 작동하는 방식과 구현할 예제에 대해 소개합니다.

HTML 정렬 목록 HTML 정렬 목록 Sep 04, 2024 pm 04:43 PM

HTML 순서 목록에 대한 안내입니다. 여기서는 HTML Ordered 목록 및 유형에 대한 소개와 각각의 예에 대해서도 설명합니다.

HTML 온클릭 버튼 HTML 온클릭 버튼 Sep 04, 2024 pm 04:49 PM

HTML onclick 버튼에 대한 안내입니다. 여기에서는 각각의 소개, 작업, 예제 및 다양한 이벤트의 onclick 이벤트에 대해 설명합니다.

See all articles