HTML5 Canvas를 사용하여 간단한 자위 게임 만들기 game_html5 튜토리얼 기술
이전에 Donnet의 DEMO에서 자위 게임을 본 후 해당 게임의 사진과 오디오를 삭제했습니다. . . . 그냥 재미로 다시 썼습니다. 단지 오락을 위해서입니다. . . . . . 저는 프레임워크를 사용하지 않고 모든 js를 직접 작성합니다. . . . . . 그래서 이것은 캔버스를 처음 접하는 사람들에게 도움이 될 수 있습니다. 작가는 오랫동안 캔버스를 연주하지 않았으며 실력이 좋지 않습니다.
더 이상 고민하지 말고 먼저 DEMO: 비행기 게임부터 시작하겠습니다. 원본 포스터는 단지 재미로 쓴 것이지 진지한 게임에 쓸 의도는 없었습니다.
본론으로 들어가 보겠습니다. 자위 게임 파일에는 index.html 항목 파일, allSprite.js 스프라이트의 논리 처리 파일, loading.js 로딩 처리 파일 및 data.js(일부 초기화된 데이터)가 포함되어 있습니다.
우선 일반 게임은 기본적으로 로딩이 필요합니다. 로딩 페이지는 스프라이트 시트 이미지, 오디오 등의 데이터를 미리 로드하는 데 사용됩니다. 이 게임은 작은 게임이므로 일부 오디오와 이미지만 로드하면 됩니다. 안에 있는 로딩 코드는 주로 다음과 같습니다. 다른 것들은 로딩 애니메이션을 만들기 위한 것입니다. 관심이 있으시면 게시하지 않겠습니다.
- loadImg:함수(데이터){
- var _this = this;
- var dataIndex = 0;
- li();
- 함수 li(){
- if(datas[dataIndex].indexOf("mp3")>=0){
- var 오디오 = 문서.createElement("audio");
- document.body.appendChild(audio);
- audio.preload = "auto";
- audio.src = 데이터[dataIndex];
- audio.oncanplaythrough = 기능(){
- this.oncanplaythrough = null;
- dataIndex ;
- if(dataIndex===datas.length){
- _this.percent = 100;
- }그렇지 않으면 {
- _this.percent = parseInt(dataIndex/datas.length*100);
- li.call(_this);
- }
- }
- }그렇지 않으면 {
- preLoadImg(datas[dataIndex] , function(){
- dataIndex ;
- if(dataIndex===datas.length){
- _this.percent = 100;
- } 그 외 {
- _this.percent = parseInt(dataIndex/datas.length*100);
- li.call(_this);
- }
- })
- }
- }
- },
- //再贴出preLoadImg적 방법
- preLoadImg(src, 콜백) 함수{
- var img = new 이미지();
- img.src = src;
- if(img.complete){
- callback.call(img);
- }else {
- img.onload = 기능(){
- callback.call(img);
- }
- }
- }
먼저 배열을 사용하여 파일에 대한 링크를 data.js에 저장한 다음 이 링크가 사진인지 오디오인지 확인합니다. 사진인 경우 preLoadImg를 사용하여 사진을 미리 로드합니다. 매우 간단합니다. 새 그림을 만든 다음 여기에 링크를 할당하고 로드한 후 다시 호출하면 됩니다. 오디오는 HTML5 오디오 DOM 개체를 생성하고 이에 대한 링크를 할당하여 로드됩니다. 오디오에는 "canplaythrough" 이벤트가 있습니다. 브라우저가 버퍼링을 위해 중지하지 않고 지정된 오디오/비디오를 계속 재생할 수 있을 것으로 예상하면 canplaythrough 이벤트가 발생합니다. , 이는 canplaythrough가 호출되면 오디오가 거의 로드되었으며 다음 오디오를 로드할 수 있음을 의미합니다. 이와 같이 모든 것이 로드된 후 콜백이 이루어지고 게임이 시작됩니다.
게임이 시작되면 여러 개체가 필요하므로 이를 하나의 스프라이트 개체로 통합했습니다. 서로 다른 개체 간의 각 프레임 이동은 동작을 사용하여 별도로 작성할 수 있습니다.
- W.Sprite = 함수(이름 , 페인터 , 행동 , 인수){
- if(이름 !== 정의되지 않음) this.name = 이름;
- if(painter !== undefine) this.painter = painter;
- this.top = 0;
- this.left = 0;
- this.width = 0;
- this.height = 0;
- this.velocityX = 3;
- this.velocityY = 2;
- this.visible = true;
- this.animating = 거짓;
- this.behaviors = 행동;
- this.rotateAngle = 0;
- this.blood = 50;
- this.fullBlood = 50;
- if(이름==="계획"){
- this.rotateSpeed = 0.05;
- this.rotateLeft = false;
- this.rotateRight = 거짓;
- this.fire = false;
- this.firePerFrame = 10;
- this.fireLevel = 1;
- }else if(이름==="별"){
- this.width = 수학.random()*2;
- this.speed = 1*this.width/2;
- this.lightLength = 5;
- this.cacheCanvas = document.createElement("canvas");
- thisthis.cacheCtx = this.cacheCanvas.getContext('2d');
- thisthis.cacheCanvas.width = this.width this.lightLength*2;
- thisthis.cacheCanvas.height = this.width this.lightLength*2;
- this.painter.cache(this);
- }else if(이름==="badPlan"){
- this.badKind = 1;
- this.speed = 2;
- this.rotateAngle = 수학.PI;
- }else if(이름==="missle"){
- this.width = missleWidth;
- }else if(이름==="boom"){
- this.width = boomWidth;
- }else if(이름==="food"){
- this.width = 40;
- this.speed = 3;
- this.kind = "레벨UP"
- }
- this.toLeft = false;
- this.toTop = false;
- this.toRight = false;
- this.toBottom = false;
- this.outArcRadius = 수학.sqrt((this.width/2*this.width/2 )*2);
- if(args){
- for(var arg in args){
- this[arg] = args[arg];
- }
- }
- }
- Sprite.prototype = {
- 생성자:Sprite,
- paint:function(){
- if(this.name==="badPlan"){this.update();}
- if(this.painter !== 정의되지 않음 && this.visible){
- if(this.name!=="badPlan") {
- this.update();
- }
- if(this.name==="plan"||this.name===" missle"||this.name==="badPlan"){
- ctx.save();
- ctx.translate(this.left , this.top);
- ctx.rotate(this.rotateAngle);
- this.painter.paint(this);
- ctx.restore();
- }그렇지 않으면 {
- this.painter.paint(this);
- }
- }
- },
- 업데이트:기능(시간){
- if(this.behaviors){
- for(var i=0;i<this.behaviors.length;i ){
- this.behaviors[i].execute(this,time)
- }
- }
XML/HTML 코드
- var SpriteSheetPainter = 함수(셀){
- this.cells = 셀 || [];
- this.cellIndex = 0;
- }
- SpriteSheetPainter.prototype = {
- advanced:function(){
- if(this.cellIndex === this.cells.length-1){
- this.cellIndex = 0;
- }
- else this.cellIndex ;
- },
- 페인트:기능(스프라이트){
- var cell = this.cells[this.cellIndex];
- context.drawImage(spritesheet , cell.x , cell.y , cell.w , cell.h , sprite.left , sprite.top , cell.w , cell.h);
- }
- }
而普는 일반적인 그림 제조 업체, 直接写一个화가, 把要画的什么东西tour写进去就行了.
<… >
- (기능(W){
- "엄격한 사용"
- var planWidth = 24,
- planHeight = 24,
- missleWidth = 70,
- missleHeight = 70,
- boomWidth = 60;
- //精灵类
- W.Sprite = 함수(이름 , 페인터 , 행동 , 인수){
- if(name !== undefine) this.name = name;
- if(painter !== undefine) this.painter = painter;
- 이것.top = 0;
- 이것.left = 0;
- 이것.width = 0;
- 이것.height = 0;
- 이것.velocityX = 3;
- 이것.velocityY = 2;
- 이것.visible = true;
- 이것.animating = false;
- 이것.behaviors = behaviors;
- 이것.rotateAngle = 0;
- 이것.blood = 50;
- 이것.fullBlood = 50;
- if(name==="계획"){
- 이것.rotateSpeed = 0.05;
- 이것.rotateLeft = false;
- 이것.rotateRight = false;
- 이것.fire = false;
- 이것.firePerFrame = 10;
- 이것.fireLevel = 1;
- }else if(name==="별" ){
- 이것.width = Math.random()*2;
- 이것.speed = 1*이것.width/2;
- 이것.lightLength = 5;
- 이것.cacheCanvas = document.createElement("canvas");
- 이것.cacheCtx = 이것.cacheCanvas.getContext('2d');
- 이것.cacheCanvas.width = 이것.width 이것.lightLength*2;
- 이것.cacheCanvas.height = 이것.width 이것.lightLength*2;
- 이것.painter.cache(이것);
- }else if(name==="badPlan" ){
- 이것.badKind = 1;
- 이것.speed = 2;
- 이것.rotateAngle = Math.PI;
- }else if(name==="missle" ){
- 이것.width = missleWidth;
- }else if(name==="boom" ){
- 이것.width = boomWidth;
- }else if(name==="음식"){
- 이것.width = 40;
- 이것.speed = 3;
- 이것.kind = "레벨UP"
- }
- 이것.toLeft = false;
- 이것.toTop = false;
- 이것.toRight = false;
- 이것.toBottom = false;
- 이것.outArcRadius = Math.sqrt((이것.width/2*이것.width/2)*2);
- if(args){
- for(var arg args){
- 이것[arg] = args[arg];
- }
- }
- }
- Sprite.prototype = {
- 생성자:Sprite,
- 페인트:기능(){
- if(이.name==="나쁜 계획" ){이것.update();}
- if(this.painter !== undefine && this .visible){
- if(이.name!=="badPlan" ) {
- 이것.update();
- }
- 만약(이것.name==="계획" ||이것.name==="미스"||이것 .name==="나쁜 계획"){
- ctx.save();
- ctx.translate(this.left , this.top);
- ctx.rotate(this.rotateAngle);
- 이것.painter.paint(이것);
- ctx.restore();
- }그 외 {
- 이것.painter.paint(이것);
- }
- }
- },
- 업데이트:기능(시간){
- if(this.behaviors){
- for(var i=0;i<이것.behaviors.length;i ){
- 이것.behaviors[i].execute(이것,time);
- }
- }
- }
- }
- // 精灵表绘器
- W.SpriteSheetPainter = 함수(cells , isloop , endCallback , spritesheet){
- 이것.cells = cells || [];
- 이것.cellIndex = 0;
- 이것.dateCount = null;
- 이것.isloop = isloop;
- 이것.endCallback = endCallback;
- 이것.spritesheet = spritesheet;
- }
- SpriteSheetPainter.prototype = {
- 고급:기능(){
- 이것.cellIndex = 이것.isloop?(이것.cellIndex===이.cells.length-1?0:이.cellIndex 1):(이.cellIndex 1);
- },
- 페인트:기능(스프라이트){
- if(이.dateCount===null){
- 이것.dateCount = new Date();
- }그밖에 {
- var newd = new Date();
- var tc = newd-this.dateCount;
- (tc>40){
- 이것.advance();
- 이것.dateCount = newd;
- }
- }
- if(이것.cellIndex<이것. cells.length || 이.isloop){
- var cell = this.cells[this .cellIndex];
- 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);
- } else if(this.endCallback) {
- 이것.endCallback.call(sprite);
- 이것.cellIndex = 0;
- }
- }
- }
- //특제제폐제
- W.controllSpriteSheetPainter = 함수(셀 , 스프라이트 시트){
- 이것.cells = cells || [];
- 이것.cellIndex = 0;
- 이것.dateCount = null;
- 이것.isActive = false;
- 이것.derection = true;
- 이것.spritesheet = spritesheet;
- }
- controllSpriteSheetPainter.prototype = {
- 고급:기능(){
- if(this.isActive){
- 이것.cellIndex ;
- if(이것.cellIndex === 이것.cells.length){
- 이것.cellIndex = 0;
- 이것.isActive = false;
- }
- }
- },
- 페인트:기능(스프라이트){
- if(이.dateCount===null){
- 이것.dateCount = new Date();
- }그밖에 {
- var newd = new Date();
- var tc = newd-this.dateCount;
- (tc>sprite.firePerFrame){
- 이것.advance();
- 이것.dateCount = newd;
- }
- }
- var cell = this.cells[this .cellIndex];
- ctx.drawImage(this.spritesheet , cell.x , cell.y , cell.w , cell.h , -planWidth/2 , -planHeight/ 2, cell.w, cell.h);
- }
- }
- W.planBehavior = [
- {실행:함수(스프라이트,시간){
- if(sprite.toTop){
- sprite.top = sprite.top
- }
- if(sprite.toLeft){
- sprite.left = sprite.left
- }
- if(sprite.toRight){
- sprite.left = sprite.left>canvas.width-planWidth/2? sprite.left : sprite.left sprite.velocityX;
- }
- if(sprite.toBottom){
- sprite.top = sprite.top>canvas.height-planHeight/2? sprite.top : sprite.top sprite.velocityY;
- }
- if(sprite.rotateLeft){
- sprite.rotateAngle -= sprite.rotateSpeed;
- }
- if(sprite.rotateRight){
- sprite.rotateAngle = sprite.rotateSpeed;

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

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

뜨거운 주제











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

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

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

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

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

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

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

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