Home Web Front-end H5 Tutorial Example process of createjs mini game development

Example process of createjs mini game development

Jul 20, 2017 pm 03:14 PM
createjs javascript Games

Implementation of the overall idea of ​​the game

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

1

2

3

4

5

6

7

8

9

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);

    }          

}

Copy after login

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.

1

2

3

4

5

6

7

8

9

// 删除越界的元素for (var i = 0, flag = true, len = that.props.length; i < len; flag ? i++ : i) {if (that.props[i]) {if (that.props[i].y > height + 300) {

            that.stage.removeChild(that.props[i]);

            that.props.splice(i, 1);

            flag = false;

        else {

            flag = true;

        }

    }

}

Copy after login

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.

1

2

3

var num = parseInt(2 * Math.random()) + 1, i;for (i = 0; i < num; i++) {var type = parseInt(10 * Math.random()) + 1;// 设置道具出现比例if (type == 1) {/绘制炸弹

        } else if ((type >= 2) && (type <= 5)) {//绘制加速道具} else if ((type >= 6) && (type <= 10)) {//绘制减速道具        }

    }

Copy after login

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

1

2

3

var time = (parseInt(3 * Math.random()) + 1);  //随机取1~3整数// 随机时间绘制障碍物setTimeout(function () {

    that.propsTmp = [];  //清空    that.drawObstacle(obj);

}, time * 400);  //400ms ~ 1200ms

Copy after login

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

1

2

3

4

createjs.Ticker.addEventListener(“tick”, tick); 

function tick(e) { if (e.paused === 1) { //处理     }

}     

createjs.Ticker.paused = 1; //在函数任何地方调用这个,则会暂停tick里面的处理 createjs.Ticker.paused = 0; //恢复游戏

Copy after login

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.

1

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

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

//放置静态资源的数组

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

}

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

;(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();

        }

    }

})()

Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Detailed explanation: Does Windows 10 have a built-in Minesweeper mini game? Detailed explanation: Does Windows 10 have a built-in Minesweeper mini game? Dec 23, 2023 pm 02:07 PM

When we use the win10 operating system, we want to know whether the built-in game Minesweeper from the old version is still saved after the win10 update. As far as the editor knows, we can download and install it in the store, as long as it is in the store Just search for microsoftminesweeper. Let’s take a look at the specific steps with the editor~ Is there a Minesweeper game for Windows 10? 1. First, open the Win10 Start menu and click. Then search and click Search. 2. Click on the first one. 3. Then you may need to enter a Microsoft account, that is, a Microsoft account. If you do not have a Microsoft account, you can install it and be prompted to register. Enter the account password and click Next. 4. Then start downloading

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to play mini games in Google Chrome How to play mini games in Google Chrome Jan 30, 2024 pm 12:39 PM

How to play mini games on Google Chrome? Google Chrome has a lot of features designed with humanistic care, and you can get a lot of diverse fun in it. In Google Chrome, there is a very interesting Easter egg game, namely the Little Dinosaur Game. Many friends like this game very much, but they don’t know how to trigger it to play. The editor will bring it to you below. Dinosaur mini game enters the tutorial. How to play mini-games on Google Chrome Method 1: [Computer disconnected from the network] If your computer uses a wired network, please unplug the network cable; if your computer uses a wireless network, please click on the wireless network connection to disconnect in the lower right corner of the computer. ② When your computer is disconnected from the Internet, open Google Chrome and Google Browse will appear.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles