background
Recently doing a clock in urban travel demand form class activities, including the main scenario map module is adopted PixiJs rendering, because before also have no contact with the H5 game development, it is also the only stay on phase of heard of PixiJs, so the development is now learning, lasted a month or so before and after, stepped on some of the pit, Also summarized some personal development experience, based on PixiJs to do some basic game function API package. As the saying goes, “To do a good job, you must sharpen your tools.” Before we reveal the mystery of these apis, let’s take a look at a few simple concepts of PixiJs to lay the foundation for further understanding.
PixiJs
PixiJs is a very fast 2D Sprite rendering engine. The rendering engine takes care of everything about rendering, helping us display, animate, and manage interactive graphics.
A few basic concepts
Application
const app = new PIXI.Application({
width: 256.// Default: 800 width
height: 256.// Default: the height is 600
antialias: true.// default: false Anti-aliasing
transparent: false.// default: false transparency
resolution: 1 // default: 1 resolution
})
document.body.appendChild(app.view)
Copy the code
Pixi creates a rectangular display area from the Application object. It automatically generates an HTML Canvas element on which all drawing is based. Application will also automatically choose to use Canvas or WebGL to render graphics, depending on browser support.
Container
Container- Container object, which creates a new layer in the application. As a container, it must be able to load child element objects. In practical development, we usually use it to group display objects.
Sprite
In Pixi, a Sprite is a special image object, which is probably one of the most commonly used objects in game development. In practice, it is used to display game image resources.
Loader
Pixi uses WebGL to render images on the GPU, so the image needs to be converted to an object that the GPU can process. This object is called texture in Pixi. To ensure efficient access, Pixi uses text cache to store and reference all textures needed by the Sprite. So how do you load an image file and turn it into the texture your GPU needs? That’s where the Loader object comes in, which can load images in any format.
With some basic concepts behind it, let’s begin today’s first API debunking.
Encapsulate an image preloading API
First of all, we need to understand why we need to preload. We mentioned that if we want to create a Sprite object, we need to fetch the texture object stored in the texture cache, and the texture object is loaded and transformed through the Loder loader. The loading process of our game is actually the process of loading image resources into texture objects through the loader.
Basic usage of Loder
// Loader mounts under shared property after pixiv5.0.x
const Loader = PIXI.Loader.shared
// Add loads the list of images
Loader.add([
'assets/fire.png'.'assets/water.png'
])
.load(callback)
// Add loads a single image and assigns a name to the resource
Loader.add('fire'.'aasets/fire.png').load(callback)
The url can be the local image address or the remote CDN image resource address
Loader.add([
{ name: 'fire'.url: 'assets/fire.png'.onComplete: () = > {} }
])
.load(callback)
Copy the code
It can be seen from the above that loader first adds to load image resources (list), load is the callback after loading, so it is packaged based on the above Loader-related API:
export default function (resource: Array<any[] >) :Promise<unknown> {
if (!Array.isArray(resource)) {
console.error(Please pass in a list of resources)
return
}
let loaderArr = []
if (Array.isArray(resource[0])) {
resource.forEach(item= > {
const onComplete = item[2]? item[2] : null
const loaderItem = {
name: item[0].// Alias of the resource
url: item[1].// Address of the resource
onComplete // The function to call when the resource is finished loading
}
loaderArr.push(loaderItem)
})
} else {
loaderArr = resource
}
return new Promise((resolve, reject) = > {
Loader.add(loaderArr)
.load(resolve)
Loader.onError.add(reject)
})
}
Copy the code
The usage is as follows:
let count = 0
// Used as the loading progress of computing resources
const loadCount = () = > {
count++
console.log('Load resource picture no${count}Zhang, timeThe ${Date.now()}`)}/ / preload
Preloader([
['fire'.'assets/fire.png', loadCount],
['water'.'assets/water.png', loadCount],
['json'.'assets/sprite.json', loadCount]
]).then(() = > {
console.log('Resource loaded successfully')
}).catch(() = > {
console.log('Resource load failed')})Copy the code
The Loder loader supports loading json files of Sprite images. So how to make Sprite based on Pixi, let’s talk about this topic.
How to make PixiJs Sprite
In the field of game development, resource loading efficiency is a major bottleneck of game performance. In order to improve game loading performance, multiple resource images of the same type are combined into one image by software synthesis, which is a Sprite image, reducing the number of network requests. The tool we usually use to create Sprite images is TexturePacker, which literally means TexturePacker. Software operation interface:
You just need to select the PixiJS option in the data format of setting list on the right, and the resulting file contains a. Json file and a. PNG /. JPG file, the former is the location of each image on the Sprite image and related information of the image, and the latter is the large size Sprite image after synthesis, in which the JSON file format is as follows:
Replace the meta/image attribute with your CDN image resource address, and fresh meat moon cake is the texture name of the image. Then replace the JSON address in the Preloader with the JSON address in your CDN, and all image object textures contained in the JSON will be loaded into the texture cache.
The TexturePacker software is handy and supports almost all of the most popular game engines in the industry, including but not limited to Cocos, Unity, Egret, PixiJs, etc. The pro version only has a 7-day trial period for one machine, the free version can’t use advanced algorithms, and the resulting Sprite graphics are flawed. Unless you are willing to pay for support, there are no other related tools to replace it. If you know, you can share it in the comments section
Afterword.
This sharing, brought to you by Bob, includes the basics of PixiJs, encapsulating a simple resource preloader, and basic instructions for using TexturePacker software to make Sprite images. We will update the API for animation playback, collision detection and adaptive application creation.
reference
- PixiJs Chinese website
- Texturepacker website
- Loader