University Students Continue Their Development Log With Cocos Creator

University Students Continue Their Development Log With Cocos Creator

We got a lot of love for the last story about this three-person team building a WeChat game. They sent out a follow-up, and we thought we share this with our English speakers as well. Here's HK-SHAO sharing his game, Star Trek.

A missile capable of automatic tracking 

In the game, you can click to launch a missile that can automatically attack the target, and you can also click to launch the missile by dragging the designated direction and strength.

In fact, the automatic tracking missile does not use any advanced pathfinding algorithm, and if it is used, the game performance would become very demanding because the number of celestial bodies in the game is extremely large, and players or UFOs can also launch dozens of missiles in a short time. If the pathfinding algorithm is used, not only could the effect not be good, but also the game performance will be greatly reduced.

So what I use is a simple algorithm based on a physical model. The principle is straightforward, and the effect is very good. It is very easy to implement in the physics engine.

This algorithm actually adds a spring of zero length between the missile and the closest target, which conforms to Hooke's law.  Fs = kx

In each frame of the game, by traversing all nearby targets, calculating the distance from the missile to the target, finding the closest target, and then multiplying the vector from the missile to the target by the scaling ratio, as the force applied to the missile on the rigid body.

In this way, the automatic tracking effect of the missile is easily achieved, and the missile can draw a beautiful curve with the particles during operation. Another advantage is that the missile can automatically accelerate when the target is far away and rely on inertia to strike the target when the distance is close (There is no damping in space, so it will not slow down).In the above picture, you can see that when I act on the missile, it’s an impulse. In fact, the effect is basically the same because the expression of the impulse is F Δ t, and every frame in the game is  basically a fixed value, Δ t.

In addition, the reason why I want to normalize the force is because I actually set linear damping for the missile. In this case, I only take the unit vector of the force so that the missile has a maximum speed instead of infinitely accelerating at long distances.

Similarly, in the game, rockets, earth, or UFOs follow the player's finger, which is actually the same principle, but it is regarded as a missile, and then its attack target is the player's fingertips (but it will not explode, let alone hurt or injure the player).

Animation and explosion effects in the game 

When playing, transitions, button clicks, exploding stars disappear, and many other things use animation. Rather than a hardline switch or directly disappear, you can bring a better visual effect to the players.

We are using Cocos Creator's easing system cc.Tween can easily implement some animations.

In the previous week, I said every entity is a node cc.Node. This node can actually have many attributes, such as position, rotation angle, color, anchor, transparency. With the easing system, you can specify an easing function to slowly change a value to another value. Here I take Manim's animation system as an example. In fact, it is still different from Cocos, but the effect is similar. (The picture comes from, which is a Chinese document written by the MK organization for Manim)

In Cocos, by slowly changing the position, size, transparency, etc. of a node through the easing system, effects such as opening and closing animations with better visual effects, gradual transitions, and shrinking and disappearing when the planet is destroyed.

The smooth function here is actually a smooth step function. To put it bluntly, it is actually very similar to the sigmoid function written in the previous weekly diary.

But it does not require exponential calculation, and the calculation efficiency is relatively high, and the stability is also very good when the value is significant. We can find out in the source code of Cocos.

Explosion effect

The explosion effect is straightforward. First, use the particle system to make an explosion, specify a time to stop the emission automatically, and then set the automatic destruction to make this node a prefab.

When a location needs to explode, instantiate the prefab as a node at this location, and then add this node to the scene. Here I take the example of igniting a gas planet to produce an explosion and giving the player an impact in the opposite direction.

The generation of planets and the effects of breathing, movement, and rotation

For mobile game performance, no more than 100 planets are calculated and rendered in each frame. Whenever the player reaches a new area, a new map is randomly generated.

In theory, players can explore an infinite, never-repeatable universe. The game map generation mechanism was completed from the beginning of this project.

The generation system will divide the map into four areas, from the inside to the outside are the screen display area, the player's field of view, the generation area, and the destruction area.

In each frame, the system will automatically generate a new celestial body in the gray area, record outside the gray area, and destroy all recorded celestial bodies in the next frame.

In the program, the generation ratio of various celestial bodies can be adjusted. In the code below, you can actually find that we have designed nearly 40 different celestial bodies.

Each new celestial body will breathe (slowly zoom in and zoom out animation), move, and rotate.

The principle of its realization is to mount different scripts for each node of various celestial bodies. At the beginning of the script, the respiration, rotation angular velocity, and movement speed are randomly generated, and then the zoom, angle, and position of this node are controlled in each update function. Take the script mounted on the planet as an example:

The construction of the solar system 

In the main interface menu of the game, you can enter the solar system and observe the entire solar system's operation.

In fact, building such a model uses the relationship between nodes and child nodes. By setting the anchor point of the parent node as the center of the sun, add an offset (simulating the effect of the ellipse's focus not at the center of the circle), and then bind the planets of the solar system to this on a node, by controlling the rotation angle of the parent node, the revolution of a planet can be edited. By controlling the rotation angle of this node, the rotation of the planet can be controlled.

Finally, particle effects and camera breathing effects were added to create a model of the solar system.

Question bank, sharing, and friends ranking

After the game is over, players can choose to answer questions to get the opportunity to start this level again. The question bank contains basic knowledge questions of astronomy, humans, and the achievements of ancient and modern Chinese. The question bank is quite large, and it is written directly in the script.

The game menu and the leaderboard interface have a share button. Players can click the button to share this mini game with others.

In fact, sharing is very simple. If it is a WeChat platform, just call the WeChat API directly. However, it should be noted that for compatibility, you must first determine whether the environment is a WeChat environment before using the WeChat API.

WeChat's shareAppMessage method can actually pass in an object to specify the title and picture to share, but because I'm lazy or unnecessary, I didn't post anything. The default title of WeChat is the name of the game and the screenshot of the current screen.

WeChat puts forward the concept of open data domain and provides some convenient APIs to implement friend rankings, but what is strange is that to ensure data security, WeChat open data domain is an independent JavaScript environment.

In Cocos, it is necessary to create another UI and related logic for the WeChat Open Data Domain project production ranking list and then merge this Cocos project into the previous game project.

However, after the merger, the game carries a new game engine js file, and the open data domain project cannot separate the engine!

In this way, the size of the project will increase by more than 1 MB, but this makes my game packaged and compiled and has exceeded the 4 MB limit stipulated by WeChat. This little game cannot be released after 4 MB. How can I break the 4 MB limit?

Break the 4MB limit 

Network load resources 

I was able to not break the 4 MB limit by compressing some of the resource files and put the game background music on the Tencent Cloud server for network loading.

Cocos has an assetManager object that provides a loadRemote method to load network resources and provides a callback function to use this resource.

Game subcontracting (Bundle) 

Divide the game into different packages, then put some packages on the network, and load the subpackages during the game. But I didn't use it, so I don't know the specifics.

Cut engine, separate engine 

In the Cocos project settings, you can delete the Cocos 2d game engine modules that are not used in the game, reducing the space occupied by the game engine code.

However, a simpler way is to use a separate engine when building the project, so that the packaged WeChat mini-games will not carry the Cocos game engine, but instead use the Cocos game engine plug-in provided by WeChat.

Resource compression 

Compression is particularly important in this regard, not only to reduce the size of game pieces but small volume resources load faster, and take up less resources. The game resources are mainly stickers, font files (ttf), audio, and text. Next, I will introduce the methods of compressing them one by one.

Texture: reduce the texture's size, convert to jpg without transparency, and check options such as smaller files in Photoshop, and you can also use image compression software to compress.

Font files: The cost-effectiveness of font file compression is particularly high! 

For my independent game, the text in the game is fixed, so the font file does not need all the Chinese characters. Therefore, we can find all the characters that appear in the game, and keep only the fonts we need in the font file, so that the file size can be significantly compressed, hundreds of kb can be compressed at a time, and the price is very high.

Here I used the Fontmin software open source on Github to delete the font (

Audio : Usually, the audio file is an mp3 file. Here I transcode it into an m4a file through ffmpeg, and merge the two channels into one channel, which can greatly reduce the volume of the audio file.

The use of ffmpeg is also very simple ffmpeg -i in.mp3 -ac 1 out.m4a. However, it should be noted that mp3 sometimes has encoding copyright issues and may not be converted to m4a.

Text : Text mainly refers to code files, because after compilation, it is ultimately js code, and js code can greatly compress the volume (by replacing variable names, deleting newline spaces, etc.). There are many js code compression software on the Internet.

Making and adjusting game maps 

Here I am using Adobe Photoshop. Sometimes black borders appear on the edges of game textures. You can use Photoshop to construct a selection, add a mask according to the selection, and then use minimize in the filter to adjust the edges until the black border disappears.

You can also change the hue of the texture through the hue adjustment function of Photoshop, so that you can instantly get a texture in another color style.

Using the noise-dust and scratch filter of Photoshop can reduce the sharp corners in the picture and sometimes get the effect of anti-aliasing. Use the filter library to get another style of picture. Of course, inverting, black and white, adjusting brightness, contrast, color saturation, etc., can also adjust the texture to better visual effects.

I simply made a game icon with Photoshop, and followed an example provided by WeChat, and spent ten minutes making a simple background image for the game.

In Photoshop, drag the material in, adjust the zoom, angle, add a background, use the pen tool to build a selection, copy the layer to change the color tone and transparency, randomly cut a starry sky texture in Shadertoy, adjust the transparency to the background, add Several filters, add a dynamic blur to the texture, adjust the angle..., and the game promotional background image is ready!


Package the Android project and build the APK 

The game's performance on the native platform is better, so I tried to package an APK, but I encountered a lot of pitfalls.

To build APK in Cocos, you must download and install JDK and Android SDK, and NDK. Android Studio is recommended both on the official website on the Internet.

I just installed and built the Android Studio environment, so I installed the SDK and NDK smoothly, and the system environment variables were also configured.

However, Java's null pointer error has always appeared when packaging with Cocos, and it has been unsuccessful for a long time. I finally found that the NDK I downloaded and installed with Android Studio is a smaller version!

Please go to the official website of Android developers to download the full version of the latest NDK and then add it to the system environment variables to ensure a response after entering ndk-build in cmd.

Finally, use Cocos to package the APK. During the packaging process, the memory and CPU will soar. In the task manager, you can see that several Cmake++ are compiling the C++ code of Cocos crazy, and the JDK is compiling the Java code of Android. The notebook compile time will be very long, but the APK file is generated successfully in the final compilation.

It seems that the APK has been automatically signed in the compilation script of Cocos, so there is no need to sign manually. However, to ensure safety, you can use a tool to generate a signature file to sign the APK manually.

HK-SHAO said that he plans to add another level, joystick control mode, scenes demonstrating multi-body movement, and more celestial science in the future. They're also scheduled to make a physical sandbox mode and change the field of view to be zoomable so that the player can control the field of view and see a larger map.

Sure enough, these young people are motivated, so we're looking forward to their next post.