search
HomeWeb Front-endH5 TutorialExample process of createjs mini game development

Example process of createjs mini game development

Jul 20, 2017 pm 03:14 PM
createjsjavascriptGames

Implementation of the overall idea of ​​the game

1. Implement a seamless background image to simulate the state of the car accelerating

this.backdrop = new createjs.Bitmap(bg);this.backdrop.x = 0;this.backdrop.y = 0;this.stage.addChild(that.backdrop);this.w = bg.width;this.h = bg.height;//创建一个背景副本,无缝连接var copyy = -bg.height;this.copy = new createjs.Bitmap(bg);this.copy.x = 0;this.copy.y = copyy;  //在画布上y轴的坐标为负的背景图长//使用createjs的tick函数,逐帧刷新舞台createjs.Ticker.addEventListener("tick", tick);function tick(e) {   if (e.paused !== 1) {//舞台逐帧逻辑处理函数that.backdrop.y = that.speed + that.backdrop.y;
        that.copy.y = that.speed + that.copy.y;if (that.copy.y > -40) {
              that.backdrop.y = that.copy.y + copyy;
        }if (that.copy.y > -copyy - 100) {
              that.copy.y = copyy + that.backdrop.y;
        }
        that.stage.update(e);
    }          
}

2. Draw obstacles randomly

Since there will definitely be many obstacles on a runway For obstacles that exceed the screen, we need to perform 'resource recovery', otherwise the game will become increasingly laggy later on.

// 删除越界的元素for (var i = 0, flag = true, len = that.props.length; i  height + 300) {
            that.stage.removeChild(that.props[i]);
            that.props.splice(i, 1);
            flag = false;
        } else {
            flag = true;
        }
    }
}

There are 3 tracks in total. We cannot have 3 props appear on the horizontal line at the same time, so we will randomly pick 1 to 2 values ​​​​to draw obstacles. We should have parameters to control the difficulty of all games, so that when the game is about to go online, the boss will feel that the game is too difficult after experiencing it... which would be very embarrassing. Therefore, we will set the proportion of acceleration objects, deceleration objects, and bombs. This proportion can be adjusted later to set the difficulty of the game.

var num = parseInt(2 * Math.random()) + 1, i;for (i = 0; i = 2) && (type = 6) && (type 

After the obstacles are drawn for the first time, the next obstacle will be drawn at a random time.

var time = (parseInt(3 * Math.random()) + 1);  //随机取1~3整数// 随机时间绘制障碍物setTimeout(function () {
    that.propsTmp = [];  //清空    that.drawObstacle(obj);
}, time * 400);  //400ms ~ 1200ms

3. Collision detection

We use an array to store the car’s Rectangular area, the rectangular area occupied by obstacles, loops through the array at each tick to see if there is overlap. If there is overlap, a collision has occurred.

Some little knowledge of createjs:

1. Pause and resume stage rendering

createjs.Ticker.addEventListener(“tick”, tick); 
function tick(e) { if (e.paused === 1) { //处理     }
}     
createjs.Ticker.paused = 1; //在函数任何地方调用这个,则会暂停tick里面的处理 createjs.Ticker.paused = 0; //恢复游戏

2. Because the car will have the effect of accelerating, decelerating, and popping bubbles. Therefore, we draw these effects in the same container to facilitate unified management. We set the name attribute for these effects, and then we can directly use getChildByName to obtain the object.

container.name = ‘role’; //设置name值car = this.stage.getChildByName(“role”);  //使用name值方便获取到该对象

3. Preload preload (preload of createjs is very practical)

I wrote the preload myself at first, and then I discovered createjs There is cross-domain processing for images. It is more troublesome to process cross-domain img by yourself, so we directly use the preloading of createjs.

//放置静态资源的数组
var manifest = [
    {src: __uri('./images/car_prop2_tyre@2x.png'), id: 'tyre'}
];
var queue = new createjs.LoadQueue();
queue.on('complete', handleComplete, this);
queue.loadManifest(manifest);
//资源加载成功后,进行处理
function handleComplete() {
   var tyre = queue.getResult('tyre');  //拿到加载成功后的img
}

Generally when making a game, we usually build a game class to host it. The following is a normal interface for the game:

;(function () {function CarGame(){}
    CarGame.prototype = {
        init:function(manifest) {this.preLoad(manifest);  //资源预加载//时间倒计时this.prepare(3, 3);  //倒计时3秒this.bindEvent(); 
        },
        render:function() {           this.drawBg(bg1);           this.drawRole(car, effbomb, effquick);           this.drawObstacle(obj);
        },//在游戏结束的时候批量销毁destroy:function(){//移除tick事件createjs.Ticker.removeEventListener("tick", this.tick);//暂停里程,倒计时clearInterval(this.changem);
            clearTimeout(this.gametime);
        },//由于期间用户可能切出程序进行其他操作,因此都需要一个暂停的接口pause:function() {//暂停里程,倒计时clearInterval(this.changem);
            clearTimeout(this.gametime);//暂停页面滚动createjs.Ticker.paused = 1;
        },//重新开始游戏reStart:function(){           this.destroy();           this.init(manifest);
        },
        gameOver:function(){           //显示爆炸效果   var car = this.stage.getChildByName("role");
           car.getChildByName('bomb').visible = true;
           car.getChildByName('quick').visible = false;           this.destroy();
        }
    }
})()

The above is the detailed content of Example process of createjs mini game development. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.