Game Development in a Front-end Context#
Development Roles and Workflow#
Team division in game development
To form the smallest yet most complete game development team, only three people are needed: a planner, a programmer, and an artist.
Of course, if you have strong enough skills, you can work as an independent developer.
Basic Workflow
Project initiation -> Prototype stage -> Alpha version -> Beta stage -> Operation stage
Why Use Game Engines#
The biggest advantage of game engines: rendering
The birth of engines was due to a company developing a game and reusing the code from the previous game for the next one, later realizing that these codes were used in almost every game, which led to the creation of an engine.
Can you create complex animations and interactions without using an engine? Of course. Is it convenient? Not necessarily.
Therefore, game engines are more like a set of solutions that improve your development efficiency when creating a specific type of product.
Need to do multi-platform porting? Solutions like React Native, Weex, Cordova can also achieve that.
Want to create physical effects? Physics engines like MatterJS and ammo.js can be used.
Want to create animations? CSS can do that too. Need something more complex? Package an animation library.
So why use a game engine?
- Provides a complete implementation solution, so you don't have to piece together or encapsulate things yourself.
- Spend less time achieving better results, especially regarding rendering efficiency and performance optimization.
- Offers common functionalities needed in game development
- Engines provide many components that can shorten development time and simplify game development.
- Professional engines usually perform better than homemade engines.
Game engines typically include renderers, 2D/3D graphic elements, collision detection, physics engines, sound, controller support, animations, and more.
Transitioning from Front-end to Game Development#
First, it is essential to have a clear understanding: Front-end development and game development are not mutually exclusive.
Many H5 games and mini-games on the market are developed using web front-end technologies rather than by dedicated game development teams or professional game developers. The reasons may include:
- The number of developers familiar with front-end development far exceeds those familiar with game development (high recruitment costs).
- The entry barrier for 2D game engines is already low enough (easy to get started).
- The implementation methods for game mechanics in H5 activities are relatively vague (blurry development boundaries).
- Many mainstream 2D game engines now support development using JavaScript and related engineering capabilities, reflecting a trend of game development aligning with web front-end development.
Thus, from the perspective of web front-end development, a 2D game engine is merely a framework or a set of solutions.
However, there are still differences in development philosophy: traditional game development focuses more on content.
Game Engines#
Common Game Engines on the Market#
Let's not discuss some PC game engines, such as:
- Unreal (Unreal Engine, representative works include "PUBG," "GTA5"),
- Source (Source Engine, representative works include "CS," "Dota2"),
- Frostbite Engine (Frostbite Engine, representative works include "Battlefield," "Need for Speed 18"),
- Unity3D (representative works include "Hearthstone," "Honor of Kings").
We need to take it step by step; let's first look at the easiest engines for front-end developers to get started with.
Specific Types of Client Game Engines#
The NVL Maker#
THE NVL Maker is a text adventure game maker.
NoCode development, requiring only writing text scripts and some configuration to generate a text adventure game.
Representative works: "Fate/stay night" and many GAL games on Steam.
Of course, due to a lack of iteration and operation, this game engine is relatively niche. There is also a library suitable for front-end development called AVG.js Project (which uses PixiJS as the rendering engine).
RPG Maker#
RPG Maker allows you to Low Code build a level-based game, suitable for developers with limited coding skills who want to express their creativity.
- The Steam bestseller "To The Moon" was created using the RPG Maker series of game engines.
Web Game Engines#
Image drawing libraries abstracted using Canvas and WebGL as underlying technologies (often accompanied by other functionalities).
General capabilities of web game engines:
- Preloading
- A large number of static materials in games, including scenes, elements, sounds, animations, models, textures, etc. If requested using native JS, coordinating request times and loading timing would be very troublesome.
- Preloading engines abstract the timing and process of loading, solving efficiency issues in loading code.
- Display and Layering, Composition Systems
- For web game programming, Canvas or WebGL is often chosen as the rendering method (think about why DOM is not used as a rendering method?).
- Canvas and WebGL, as low-level APIs, have very basic interfaces, requiring a lot of coding to write simple displays. Moreover, there is no composition or layering between graphics, making it difficult to handle element composition and layering issues.
- Rendering engines and layering, composition systems have emerged.
- Animation Systems: Animations are often divided into tween animations and frame-by-frame animations; here we discuss tween animation systems.
- Tween animation systems in native JS need to be considered alongside frame rendering, resulting in a massive amount of code and thought, with low abstraction levels, hence the need for game engine animation systems.
- Sound and Audio Systems:
- Games require more three-dimensional and timely feedback compared to ordinary web front-end applications, and sound and audio are crucial components of that feedback.
- Sound and audio systems often include integrated functions for sound playback, volume, cutoff, pause, etc.
Cocos#
Advantages
- Good platform support
- Comprehensive game functionality support
- Good ecosystem
Disadvantages
- 3D capabilities are still under development
- Rapid version iteration
Laya#
Advantages
- Mature 3D capabilities, claiming a 90% market share
- Supports JS, TS, AS
- Small engine size
Disadvantages
- Interface capabilities are not user-friendly
- Poor ecosystem
Egret#
Advantages
- Relatively complete toolchain
- Good third-party library support
- Strong enterprise customization capabilities
Disadvantages
- Update iterations face bottlenecks
- Poor ecosystem
You can see that the interfaces of the above game engines are quite similar.
CreateJS & Phaser#
These two game engines do not have a visual interface.
Using CreateJS as an example:
It is a collection of multiple libraries.
- EASELS (controls material display and composition), TWEENJS (controls material tween animations), SOUNDJS (controls sound), PRELOADJS (controls loading), which together constitute the game through preloaded material displays, animations, and sounds. The Phaser game engine, in addition to the display, sound, animation, and loading systems based on CreateJS,
- also designs advanced features such as cameras, physics engines, built-in browsers, and plugin systems.
Functional Engines#
Large game engines are often assembled from smaller functional engines. A large game engine typically includes rendering engines, physics engines, UI systems, sound systems, animation systems, particle systems, skeletal systems, network systems, etc. The most critical components are the rendering engine and the physics engine. Functional engines focus on specific capabilities and are characterized by being small and fully functional. Particularly, Pixi.js and Three.js are often mistakenly thought to be complete game engines, but they are rendering engines focused on rendering capabilities.
Here are a few functional engines you may frequently encounter:
- Pixi.js
- Strong 2D rendering capabilities (especially WebGL)
- Complex animation systems, complex image rendering forms, creating your own 2D game engines, etc.
- Three.js
- Strong 3D rendering capabilities
- Suitable for 3D effect demonstrations or 3D-style H5 games or mini-games
- Box2D.js
- 2D physics engine
- Object simulation capabilities
Technical Architecture of 2D Game Engines#
Taking the architecture of the Cocos engine as an example:
-
render (renderer), collision, physical
-
Adapters for PC, iOS, Android, H5... and construction tools for various platforms
-
Runtime
Rendering Principles of Web Game Engines#
Taking Pixi's rendering process as an example
The general process is as follows:
-
Create a Renderer, obtain its view (a canvas object), and add it to the DOM Tree (or specify an existing canvas object in the DOM Tree as the view).
-
In the MainLoop, call Renderer.render() and pass in a DisplayObject as the root node for rendering.
-
Starting from the root node of the scene tree, perform a depth-first traversal in order of zIndex from small to large, rendering each node and drawing the entire scene from back to front (CanvasRenderer).
-
The execution process of the WebGL render method (popular science)
render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { // 1. Apply transformation (GPU level) this.projection.transform = transform; // 2. Render texture binding and BatchRendering processing this.renderTexture.bind(renderTexture); this.batch.currentRenderer.start(); // 3. Execute element rendering, adding vertex, index, and texture data to BatchRendering displayObject.render(); // 4. Execute the renderer's drawing method this.batch.currentRenderer.flush(); // Process the texture based on the passed Clear and renderTexture parameters... // 5. Clear transformation this.projection.transform = null; }
-
The execution process of the Canvas render method
Taking Pixi's rendering process as an example:
render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { const context = this.context; // 1. Push the current state onto the state stack context.save(); // 2. Initialize transformation and style properties context.setTransform(1, 0, 0, 1, 0, 0); context.globalAlpha = 1; this._activeBlendMode = BLEND_MODES.NORMAL; this._outerBlend = false; context.globalCompositeOperation = this.blendModes[BLEND_MODES.NORMAL]; // 3. Execute element rendering const tempContext = this.context; this.context = context; displayObject.renderCanvas(this); this.context = tempContext; // 4. Restore the previous state from the state stack context.restore(); }
Skill Tree for Game Development#
PixiJS + Web Development#
Introduction to Pixi#
The official website of PixiJS at first glance looks like a game engine, but it also clearly states: "Create beautiful digital content with the fastest and most flexible 2D WebGL renderer" (translated by Google).
- It is essentially still a rendering engine, and it claims to do it best.
- It can do more than just games; it can also use this technology to create any interactive content, such as apps, and you can build your own game engine based on it (AVG.js and Phaserjs's rendering engine is Pixi).
Prerequisite technology stack
- Basic web front-end development
- Experience with JSON files and understanding their purpose
- Familiarity with the Canvas drawing API
Loading a Game Mechanic in a Web Project#
-
Installation and Import
- Install via npm or include it through a script tag
<script src="pixi.min.js"></script>
- Install via npm or include it through a script tag
-
Create a Pixi Application and Stage
// First, create a display rectangle area; when creating a Pixi application instance, a canvas is automatically created, and it calculates how to display your image in the canvas. let app = new PIXI.Application({width: 250, height: 250 }); // app.stage is a [stage] that contains everything you want to display with Pixi. // Second, add the canvas to the DOM Tree. At this point, a pure black interface of 250*250 is displayed. document.body.appendChild(app.view); // PIXI.Application calculates whether to use Canvas or WebGL to render images based on the current browser's support, generally preferring WebGL. // If you want the Canvas to be transparent or force it to use Canvas mode, you can set let app = new PIXI.Application({ width: 250, height: 250, transparent: true, forceCanvas: true, });
-
Display an Image
Concept understanding: Sprite
-
You may have heard of the concept of sprite sheets while learning CSS, but it is different. In Pixi or more game engines, the concept of Sprite is an object used to hold images, and you can control its size, position, and other properties to create interactions and animations. Creating and controlling Sprites is an essential part of learning Pixi.
-
To create a Sprite, you need to understand how to load images into Pixi. Here, there is a concept: Texture Cache (referring to images that can be processed by the GPU)
-
Pixi uses a texture cache to store and reference the textures needed for Sprites. The name string of the texture is the image's address. For example, if there is an "images/cat.png", we can use
PIXI.utils.TextureCache["images/cat.png"]
to find it in the texture cache. -
Of course, to find it, you must first convert it into a texture stored in the texture cache, which can be done using
PIXI.loader
to load it.PIXI.loader.add("images/cat.png").load(res => { let sprite = new PIXI.Sprite( PIXI.loader.resources["images/cat.png"].texture ); });
-
-
Now that a Sprite has been created, the next step is to display it by adding it to the stage.
app.stage.addChild(sprite);
-
-
Make the Image Move
Earlier, we mentioned that you can set the position and size of a Sprite; what if I want it to move one pixel per frame? This is where the game loop comes into play. (Any game loop code will be called once per frame)
app.ticker.add(delta => { sprite.x += 1; });
-
Then add a bit of detail CacheAsBitmap - PixiJS Examples
Cocos Creator Editor Development#
Introduction to Cocos Creator#
Q: Is Cocos Creator a game engine?
A: Cocos + interface editing. It is a complete game development solution that includes a lightweight and efficient cross-platform game engine and various graphical interface tools that allow you to develop games more quickly.
Integrated Capabilities of the Editor#
Cocos Workflow#
Download and create -> Design scenes & develop -> Preview and debug -> ANYSDK integration -> Package and publish -> Cocos Runtime
The above image shows the workflow of Cocos.
Creating a Project#
Building a Scene#
Cocos's workflow is centered around data-driven and scene-based development with a component-based approach.
As you can see, there is no need to understand CSS, and you can directly adjust the image size through the property inspector on the right, which is low-code.
Nodes (cc.Node) are entities that carry components, and we mount various functional components (such as Sprite, Spine, Label) onto nodes to give them various appearances and functionalities.
Nodes form a node tree, which affects the actual rendering hierarchy.
Importing Resources + Displaying Resources#
You can drag files from other windows in the operating system into the resource manager panel in Cocos Creator to import resources from external sources. This operation will automatically copy the resource files to the project's resource folder and complete the import. Then, dragging the image into the hierarchy manager will generate a cc.Sprite.
Script Mounting#
test.js
const { property, ccclass } = cc._decorator;
@ccclass
export default class TestComp extends cc.Component {
onLoad() {
console.log('TestComp onload');
}
start() {}
update(dt) {}
onDestroy() {}
}
Then, mount the script to the corresponding node in Cocos Creator.
Running and Debugging#
Game Launch#
Building#
You can choose multiple platforms when building the game, and the products will be generated accordingly, such as Web and Mobile.
The products can be directly deployed on the corresponding platforms, such as deploying web products to servers and mini-game products to developer platforms.
Where are Mini Games "Mini"?#
Differences in Game Publishing Platforms#
-
Logically, there is no difference in the games.
-
Differences in game engines
-
Differences in platform APIs (the most critical aspect to focus on)
-
Rendering differences are not significant
Important Concepts in Game Development#
Inspire Creativity
- Treat the game development process as a game, challenging yourself to create a high-quality game within the constraints (your own tech stack, limited themes, limited resources) through creativity and technical skills!
- Don't let creativity be constrained.
Summary and Reflections#
This lesson discussed the differences between game development in a front-end context and traditional game development, introduced some game engines, presented a skill tree for game development, and briefly outlined the steps for game development using Cocos Creator or PixiJS.
Most of the content referenced in this article comes from the class of teacher ycaptain.