Quick Start: Making Your First 2D Game

Platform jumping games are a very common and popular game genre, ranging from simple games on the original NES console to large-scale games made with complex 3D technology on modern gaming platforms. You can always find platform jumping games.

In this section, we will demonstrate how to use the 2D features provided by Cocos Creator to create a simple platform jumping game.

Environment Setup

Download Cocos Dashboard

Visit the Cocos Creator official website to download the latest version of Cocos Dashboard, which allows for unified management of the Cocos Creator versions and your projects. After installing, open the Cocos Dashboard.

dashboard

Install Cocos Creator

download-editor

In the Editor tab, click on the Install button for the desired version to install the editor, Cocos Creator.

We usually recommend using the latest version of Cocos Creator to get started. it will obtain more features and support.

Create Project

In the Project tab, find the Create button, select Empty(2D).

create-2d-project

Next, just enter your project name in the highlighted field shown in the image above.

For example, you could input: cocos-tutorial-mind-your-step-2d.

Let’s make a game that is similar to the one in Quick Start: Making Your First 3D Game.

If you haven’t read Quick Start: Making Your First 3D Game yet, that’s okay. In this section, we’ll assume you haven’t used Cocos Creator before, and we’ll start from scratch!

Without further ado, let’s get started.

Create the Character

In a 2D game, all visible objects are made of images, including the character.

To keep things simple, we’ll be using the images that come bundled with Cocos Creator to create our game. These images can be found in internal/default_ui/.

In Cocos Creator, we use a Sprite node ( a node with a Sprite component ) to show an image.

To create a new node of type Sprite, right-click in the Hierarchy panel, select “Create”, and then choose “2D -> Sprite” from the pop-up menu.

Right-click in the Hierarchy and select “Create” from the pop-up menu, and we can see different types of nodes. Here, we select “2D -> Sprite” to create a new Sprite node.

create-sprite.png

Next, we find the internal/default_ui/default_btn_normal and assign it to the Sprite Frame property of the Sprite node we just created.

create-sprite.gif

Next, create an Empty node and name it “Player”:

create-player.gif

If you didn’t name the node when you created it, there are two ways to change its name:

  • In the Inspector panel, find the name and rename it
  • In the Hierarchy, select the node then press F2

We can adjust the parent-child relationship of nodes by dragging and dropping them in the Hierarchy. Here, drag the Sprite node onto the Player node to make it a child, then rename the Sprite node to “Body”.

create-body.gif

Note

  • The hierarchy relationship determines the rendering order. if may cause the node to not be visible when the order is wrong.
  • 2D/UI elements must be under a Canvas node in order to be visible.
  • The layer of 2D/UI elements must be set to UI_2D

Next, Let’s adjust the position’s Y of the Body node to 40:

40-on-y.png

Finally, let’s adjust the color of the Body.

In the Inspector panel, find the Color property and expand it, then set the color to red.

to-red.png

The First Script

Scripts, also known as code, are used to implement game logic, such as character movement, jumping, and other gameplay mechanics.

Cocos Creator uses TypeScript as its scripting programming language. It has simple and easy-to-learn syntax, a large user base, and widespread applications. You can encounter it in web development, app development, game development, etc.

Creating a script component in Cocos Creator is very simple. All you need to do is right-click in the Assets Manager window, and select “Create -> TypeScript -> NewComponent” option.

Quick Start: Making Your First 2D Game - 图10

For ease of management, it is often recommended to create a folder named Script to put all of your scripts in.

Next, right-click on the Scripts folder, and create a new script component named PlayerController to control the player.

create-scripts.gif

The engine will generate the following code for the script component that we just created.

  1. import { _decorator, Component, Node } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('PlayerController')
  4. export class PlayerController extends Component {
  5. start() {
  6. }
  7. update(deltaTime: number) {
  8. }
  9. }

Note Cocos Creator uses a Node + Component architecture, meaning that a component must be attached to a node in order to function. Scripts in Cocos Creator are also designed as components.

So, let’s drag the PlayerController script onto the Inspector of Player node.

add-player-controller.gif

You should see that a PlayerController component has been added to the Player node.

Note: You can also click on the Add Component button to add different types of components. import { _decorator, Component, Node } from 'cc'

Map

A map in a game is an area where your character can move around and interact within a game.

As mentioned before, all visible objects in 2D games are made up of images. The map is no exception.

Just like the steps we used to create the Body node, we will now create an object called Box which will be used to construct the map.

  • Right-click in the Hierarchy
  • Create a Sprite node by selecting “Create -> 2D Objects -> Sprite” through the pop-up menu.
  • Name it as “Box”
  • Select the “Box” node, set its Sprite Frame property by using internal/default_ui/default_btn_normal

create-box.png

Prefab

A prefab is a special type of resource that can save the information of a node as a file. so that it can be reused in other situations.

In Cocos Creator, creating a prefab is quite simple. We just need to drag the node into the Assets Manager window, a *.prefab file will be automatically generated.

Now, let’s create a folder named Prefab in the Assets Manager window, which will be used to organize all prefabs together.

Then, find the Box node and drag it to the Prefab folder, a prefab file named “Box” will be generated.

The box node in the hierarchy can be deleted, because it won’t be used when the game is running. Instead, we will create nodes in the script using Box.prefab to build the game map during gameplay.

create-box-prefab.gif

Tips: Generally, We will use different folders to manage different types of resources. It’s a good habit to keep your project well-organized.

Scene

In the game engine, a scene is used to manage all game objects. It contains characters, maps, gameplay, UI. you name it in a game.

A game can be divided into different scenes based on its functionalities. Such as the loading-scene, start-menu-scene, gameplay-scene, etc.

A game requires at least one scene to start.

So, in Cocos Creator, an unsaved empty scene will be opened by default, just like the one we are currently editing.

To ensure that we can find this scene the next time we open Cocos Creator, we need to save it.

First, let’s create a folder named “Scene” to save our scenes in the Assets Manager window.

scene-dir.png

Then, press the Ctrl + S shortcut key.

Since it is the first time we are saving this scene, the scene-saving window will pop up.

We choose the “Scene” folder that we just created as the location, and name it “game.scene”. Click save.

save-scene.png

Now the scene is saved. We can see a scene resource file named “game” under the assets/Scene folder in the Assets Manager window.

saved-scene.png

The scene now can be observed as below, the red block represents the player, and the white represents the ground.

scene.png

Don’t forget to press Ctrl + S shortcut key to save your scene when there are changes to the scene. Avoid losing work progress due to unexpected events such as power outages.

Make the character move

We have created the “Player” node before, but it can not move.

Next, we will add code and animations to control its movement and make it move.

PlayerController

The player should have the following behaviors:

  • it starts jumping when the mouse is clicked.
  • When it has been jumping for a certain amount of time, the jumping ends.

To achieve the above goals, we need to add some methods in the PlayerController component.

  • Listen for mouse-click events

    1. onMouseUp(event: EventMouse) {}
  • Jump according to the given steps

    1. jumpByStep(step: number) {}
  • Calculate the position of the player

    1. update (deltaTime: number) {}

Next, let’s complete these methods.

Listen for mouse-click events

Cocos Creator supports various common control devices, such as the mouse, keyboard, touchpad, and gamepad. You can easily access the relevant content through Input class.

For ease of use, Cocos Creator provides a global instance object input for the Input class.

Note It’s easy to confuse, input is the instance, and Input is the class.

To make the onMouseUp method be called by the engine when the mouse is clicked, we need to add the following code to the start method.

  1. start () {
  2. input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
  3. }

The onMouseUp method has an event parameter of type EventMouse.

Through the event.getButton() method, we can get which button of the mouse is clicked.

Add the following code to the onMouseUp method:

  1. onMouseUp(event: EventMouse) {
  2. if (event.getButton() === EventMouse.BUTTON_LEFT) {
  3. this.jumpByStep(1);
  4. } else if (event.getButton() === EventMouse.BUTTON_RIGHT) {
  5. this.jumpByStep(2);
  6. }
  7. }

In the EventMouse class, there are three values have been defined:

  • public static BUTTON_LEFT = 0;
  • public static BUTTON_MIDDLE = 1;
  • public static BUTTON_RIGHT = 2;

The code has implemented that:

  • When the left mouse button is clicked, the player jumps forward one step.
  • When the right mouse button is clicked, the player jumps forward two steps.

Move the player

In our game, the player moves horizontally to the right, so we need to use a simple physics formula as below:

  1. P_1 = P_0 + v*t

Where P_1 is the final position, P_0 is the original position, v is the speed of the object, and t is the unit time.

Final Position = Original Position + Speed * deltaTime

The update function in the PlayerController component will be automatically called by the game engine. And also pass in a deltaTime parameter.

  1. update (deltaTime: number) {}

The times that update will be called per second is determined by the frame rate (also known as FPS) when the game running.

For example, if a game is running at 30 FPS, the deltaTime will be 1.0 / 30.0 = 0.03333333… second.

In game development, we use deltaTime as the t in the physics formula to ensure consistent movement results at any frame rate.

Here, let’s add some properties needed for calculating player movement PlayerController component.

  1. //used to judge if the player is jumping.
  2. private _startJump: boolean = false;
  3. //the number of steps will the player jump, should be 1 or 2. determined by which mouse button is clicked.
  4. private _jumpStep: number = 0;
  5. //the time it takes for the player to jump once.
  6. private _jumpTime: number = 0.1;
  7. //the time that the player's current jump action has taken, should be set to 0 each time the player jumps, when it reaches the value of `_jumpTime`, the jump action is completed.
  8. private _curJumpTime: number = 0;
  9. // The player's current vertical speed, used to calculate the Y value of position when jumping.
  10. private _curJumpSpeed: number = 0;
  11. // The current position of the player, used as the original position in the physics formula.
  12. private _curPos: Vec3 = new Vec3();
  13. //movement calculated by deltaTime.
  14. private _deltaPos: Vec3 = new Vec3(0, 0, 0);
  15. // store the final position of the player, when the player's jumping action ends, it will be used directly to avoid cumulative errors.
  16. private _targetPos: Vec3 = new Vec3();

Now, what we need to do next is very simple:

  • Calculating the data needed for player movement in the jumpByStep method.
  • Processing player movement in the update method.

In the jumpByStep method, we add the following code:

  1. jumpByStep(step: number) {
  2. if (this._startJump) {
  3. //if the player is jumping, do nothing.
  4. return;
  5. }
  6. //mark player is jumping.
  7. this._startJump = true;
  8. //record the number of steps the jumping action will take.
  9. this._jumpStep = step;
  10. //set to 0 when a new jumping action starts
  11. this._curJumpTime = 0;
  12. //because the player will finish the jumping action in the fixed duration(_jumpTime), so it needs to calculate jump speed here.
  13. this._curJumpSpeed = this._jumpStep / this._jumpTime;
  14. //copy the current position of the node which will be used when calculating the movement.
  15. this.node.getPosition(this._curPos);
  16. //calculate the final position of the node which will be used when the jumping action ends.
  17. Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep, 0, 0));
  18. }

Vec3 is the vector class in Cocos Creator, the name is short for Vector3, which has 3 components, x,y,z. all vector operations are placed in Vec3 class. Such as Vec3.add, Vec3.subtract etc.

In Cocos Creator, 2D games also use Vec3 as the property type for position, scale, and rotation. Just ignore the irrelevant components, e.g. the z component in position.

Next, let’s calculate the movement of the player while jumping.

In this game, the player only moves when jumping, and keeps still when not jumping.

Let’s add the following code to the update method in PlayerController.

  1. update (deltaTime: number) {
  2. //we only do something when the player is jumping.
  3. if (this._startJump) {
  4. //accumulate the jumping time.
  5. this._curJumpTime += deltaTime;
  6. //check if it reaches the jump time.
  7. if (this._curJumpTime > this._jumpTime) {
  8. // When the jump ends, set the player's position to the target position.
  9. this.node.setPosition(this._targetPos);
  10. //clear jump state
  11. this._startJump = false;
  12. } else {
  13. //if it still needs to move.
  14. // copy the position of the node.
  15. this.node.getPosition(this._curPos);
  16. //calculate the offset x by using deltaTime and jumping speed.
  17. this._deltaPos.x = this._curJumpSpeed * deltaTime;
  18. //calculate the final pos by adding deltaPos to the original position
  19. Vec3.add(this._curPos, this._curPos, this._deltaPos);
  20. //update the position of the player.
  21. this.node.setPosition(this._curPos);
  22. }
  23. }
  24. }

Now, click the Preview button at the top of Cocos Creator.

preview-menu.png

The Player will move by clicking the mouse buttons.

without-scale.gif

As you can see, the player only moves a little each time you click the mouse button.

This is because we use pixels/s as the unit of speed for the Player.

  1. this._curJumpSpeed = this._jumpStep / this._jumpTime;

The above code indicates that the player will only move one pixel per step.

In fact, we want the Player to move a certain distance per step.

To fix this, we need to add a constant to express the step size.

Below, the BLOCK_SIZE is used for this purpose.

  1. import { _decorator, Component, Node } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. //
  4. export const BLOCK_SIZE = 40;
  5. @ccclass('PlayerController')
  6. export class PlayerController extends Component {
  7. //...
  8. }

As you can see, in TypeScript:

  • A constant can be defined outside of the class and exported separately.
  • Values declared as const cannot be modified and are often used for fixed configurations.

Next, find the code line in jumpByStep method:

  1. this._curJumpSpeed = this._jumpStep / this._jumpTime;

Change it to:

  1. this._curJumpSpeed = this._jumpStep * BLOCK_SIZE/ this._jumpTime;

Here is the updated jumpByStep:

  1. jumpByStep(step: number) {
  2. if (this._startJump) {
  3. return;
  4. }
  5. this._startJump = true;
  6. this._jumpStep = step;
  7. this._curJumpTime = 0;
  8. this._curJumpSpeed = this._jumpStep * BLOCK_SIZE/ this._jumpTime;
  9. this.node.getPosition(this._curPos);
  10. Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep* BLOCK_SIZE, 0, 0));
  11. }

Restart the game, and you can see that the distance of the player’s movement is as expected now.

with-scale.gif

At this moment, the code of PlayerController is as follows.

  1. import { _decorator, Component, Vec3, EventMouse, input, Input } from "cc";
  2. const { ccclass, property } = _decorator;
  3. export const BLOCK_SIZE = 40;
  4. @ccclass("PlayerController")
  5. export class PlayerController extends Component {
  6. private _startJump: boolean = false;
  7. private _jumpStep: number = 0;
  8. private _curJumpTime: number = 0;
  9. private _jumpTime: number = 0.3;
  10. private _curJumpSpeed: number = 0;
  11. private _curPos: Vec3 = new Vec3();
  12. private _deltaPos: Vec3 = new Vec3(0, 0, 0);
  13. private _targetPos: Vec3 = new Vec3();
  14. start () {
  15. input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
  16. }
  17. reset() {
  18. }
  19. onMouseUp(event: EventMouse) {
  20. if (event.getButton() === 0) {
  21. this.jumpByStep(1);
  22. } else if (event.getButton() === 2) {
  23. this.jumpByStep(2);
  24. }
  25. }
  26. jumpByStep(step: number) {
  27. if (this._startJump) {
  28. return;
  29. }
  30. this._startJump = true;
  31. this._jumpStep = step;
  32. this._curJumpTime = 0;
  33. this._curJumpSpeed = this._jumpStep * BLOCK_SIZE/ this._jumpTime;
  34. this.node.getPosition(this._curPos);
  35. Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep* BLOCK_SIZE, 0, 0));
  36. }
  37. update (deltaTime: number) {
  38. if (this._startJump) {
  39. this._curJumpTime += deltaTime;
  40. if (this._curJumpTime > this._jumpTime) {
  41. // end
  42. this.node.setPosition(this._targetPos);
  43. this._startJump = false;
  44. } else {
  45. // tween
  46. this.node.getPosition(this._curPos);
  47. this._deltaPos.x = this._curJumpSpeed * deltaTime;
  48. Vec3.add(this._curPos, this._curPos, this._deltaPos);
  49. this.node.setPosition(this._curPos);
  50. }
  51. }
  52. }
  53. }

Player Animation

For 2D game development, Cocos Creator supports various types of animation, including keyframe animation, Spine, DragonBones, and Live2D.

In this tutorial, the jump animation of the Player is very simple and it is enough to use keyframe animation.

Using Cocos Creator’s built-in animation editor, it’s easy to make it.

Let’s take a step-by-step approach to creating it.

First, let’s add the Animation component to the Body node of the Player.

add-animation.png

In the Assets Manager window, create a new folder named “Animation”, Inside that folder, create a new AnimationClip named “oneStep”.

create-clip-onestep.gif

In the Hierarchy, select the “Body” node and drag “oneStep” from the Animation folder onto the “Clips” property in the Inspector panel.

assign-clip.gif

In the editor console area, switch to the “Animation” tab and click the “Enter animation editing mode” button:

enter-anim-editing-mode.png

In the animation editor, we add a track for the node’s position property.

add-position-track.png

After adding the track, we can set the indicator of the current frame to a certain frame and then change the position of the node, the current frame will be set to be a keyframe automatically.

Both modify the value on the Inspector panel and dragging the node in the scene can change the position of a node.

add-keyframes.gif

Finally, we have the following keyframes:

  • 0 frame:set position to x = 0, y = 40
  • 10 frame: set position to x = 0, y = 120
  • 20 frame: set position to x = 0, y = 40

Don’t forget to click the Save button to save it.

You can click the Play button to preview the animation clip.

preview-oneStep.gif

Follow the steps of making oneStep animation, and make another one: twoStep.

create-twostep.gif

After completing the animation creation, click the Close button to exit the Animation editing mode.

Play animations in code

Next, let’s add some code lines into PlayerController to play the animation we’ve just made.

Playing an animation using TypeScript in Cocos Creator is quite simple:

  1. animation.play(animName);
  • animation is the Animation component on Body node.
  • play is the method of Animation component to play animation
  • animName is the name of an animation file that you want to play

In Cocos Creator, we must ensure the animation which will be played is included in the clips of the node’s Animation component,

Add the following code at the beginning of the PlayerController class:

  1. @ccclass("PlayerController")
  2. export class PlayerController extends Component {
  3. @property(Animation)
  4. BodyAnim:Animation = null;
  5. //...
  6. }

Note:The TypeScript and Cocos Creator both have an Animation class, please make sure the Animation is included in the code line import { ... } from "cc". Otherwise, the code will use the Animation from TypeScript, and unpredictable errors may occur.

Here we added a property named BodyAnim and added @property above it. This syntax is called: Decorator. The @property decorator allows the editor to be aware of the type of BodyAnim and display the exported properties of the Animation component on the Inspector panel.

To make sure there is a code line in your PlayerController file as below, or the code will fail to compile.

  1. `const { ccclass, property } = _decorator;`

Here _decorator is a class containing all of the decorators that can be used in Cocos Creator, it should be imported from namespace cc before using it.

The related code lines are as follows:

  1. import { _decorator, Component, Vec3, EventMouse, input, Input, Animation } from "cc";
  2. const { ccclass, property } = _decorator;

In jumpByStep method, we add to the following code lines:

  1. if (this.BodyAnim) {
  2. if (step === 1) {
  3. this.BodyAnim.play('oneStep');
  4. } else if (step === 2) {
  5. this.BodyAnim.play('twoStep');
  6. }
  7. }

Now, the jumpByStep method is like this:

  1. jumpByStep(step: number) {
  2. if (this._startJump) {
  3. return;
  4. }
  5. this._startJump = true;
  6. this._jumpStep = step;
  7. this._curJumpTime = 0;
  8. this._curJumpSpeed = this._jumpStep * BLOCK_SIZE/ this._jumpTime;
  9. this.node.getPosition(this._curPos);
  10. Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep* BLOCK_SIZE, 0, 0));
  11. //the code can explain itself
  12. if (this.BodyAnim) {
  13. if (step === 1) {
  14. this.BodyAnim.play('oneStep');
  15. } else if (step === 2) {
  16. this.BodyAnim.play('twoStep');
  17. }
  18. }
  19. }

Back to the Cocos Creator, select Player node, and then drag the Body node on the BodyAnim property.

assign-body-anim.gif

The engine will automatically get the Animation component on the Body node and assign it to BodyAnim. As a result, the PlayerController‘s BodyAnim property references the Animation component of Body node.

Hit Play button at the top of Cocos Creator to preview, you can see the Player jumps while clicking the mouse buttons.

preview-anim.gif

Because of using the unified.

Here we use a unified jumpTime value, jumpTime = 0.1, But since the duration of the two animations is not the same, you can find it a little weird when animations are played.

To solve this, it’s better to use the real duration of the animations as the value of jumpTime.

  1. // Get jump time from animation duration.
  2. const clipName = step == 1? 'oneStep' : 'twoStep';
  3. const state = this.BodyAnim.getState(clipName);
  4. this._jumpTime = state.duration;

jumptime-with-duration.gif

GameManager

In game development, we can manually place nodes using Box.prefab to build the map, but the map will be fixed. To make the map change whenever the game starts and provide some surprises for the players, we can randomly build the map in code.

Now, let’s create a new TypeScript component called GameManger in the Assets Manager window to archive this.

Note:If you forget to rename the script or input the wrong name you don’t want to use when creating a script component, The best way to fix it is to delete it and create a new one. Note:If you modify the name of a script, the content in the script file will not change accordingly.

After creating the GameManger script component, let’s create a new node named GameManager, then attach GameManager to it.

Note Generally, we can attach the GameManager script component to any node in the scene, but for keeping the project structure well-organized, we usually create a node with the same name and attach the GameManager to it. This rule applies to all XXXManager script components.

create-game-manager.png

To build the map, we will use the Box.prefab to create the nodes.

So, the first thing we need to do is to add a property to the GameManager class for referencing the Box.prefab.

Now, the content of the GameManager class is as follows:

  1. import { _decorator, Component, Prefab } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('GameManager')
  4. export class GameManager extends Component {
  5. @property({type: Prefab})
  6. public boxPrefab: Prefab|null = null;
  7. start(){}
  8. update(dt: number): void {
  9. }
  10. }

Go back to the Cocos Creator, select the GameManager node, and drag Box prefab onto the boxPrefab property of GameManager node.

assign-box-prefab.gif

The map in this game is made up of two types of blocks. the two types of blocks alternate to form the map.

  • None: an empty block, if the Player steps on a block of this type, the game is over.
  • Stone: The Player can stand on.

To make the code more understandable, we often use enum to define the types of objects.

We define an enum named BlockType which has two elements as below.

  1. enum BlockType{
  2. BT_NONE,
  3. BT_STONE,
  4. };

In TypeScript, if the first element of an enum hasn’t been given a value, it will take 0 as default. Here, BT_NONE = 0, BT_STONE = 1.

In the following code, you can see how we use it.

We put it above the definition of GameManager class, and without giving it an export. As a result, it only can be used in this single file.

Next, it is needed to determine where to place a new block. We add a property named roadLength to record the length of the road made up of the blocks.

To manage all the types of blocks we have created, we add the private property _road of type Array to store the generated block types.

Now, the code of the GameManager is as follows:

  1. import { _decorator, CCInteger, Component, Prefab } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. enum BlockType{
  4. BT_NONE,
  5. BT_STONE,
  6. };
  7. @ccclass('GameManager')
  8. export class GameManager extends Component {
  9. @property({type: Prefab})
  10. public boxPrefab: Prefab|null = null;
  11. @property({type: CCInteger})
  12. public roadLength: number = 50;
  13. private _road: BlockType[] = [];
  14. start() {
  15. }
  16. }

The flow of constructing the map is as follows:

  • Clear all data when the game starts
  • The type of the first block is always BlockType.BT_STONE to prevent the Player from falling off.
  • The type of a block after a block with the type of BlockType.BT_STONE should always be BlockType.BT_STONE.

Next, let’s add the following method to GameManger.

  • Method to generate the map:

    1. generateRoad() {
    2. this.node.removeAllChildren();
    3. this._road = [];
    4. // startPos
    5. this._road.push(BlockType.BT_STONE);
    6. for (let i = 1; i < this.roadLength; i++) {
    7. if (this._road[i - 1] === BlockType.BT_NONE) {
    8. this._road.push(BlockType.BT_STONE);
    9. } else {
    10. this._road.push(Math.floor(Math.random() * 2));
    11. }
    12. }
    13. for (let j = 0; j < this._road.length; j++) {
    14. let block: Node | null = this.spawnBlockByType(this._road[j]);
    15. if (block) {
    16. this.node.addChild(block);
    17. block.setPosition(j * BLOCK_SIZE, 0, 0);
    18. }
    19. }
    20. }

    Math.floor: rounds down and returns the largest integer less than or equal to a given number. refer to Math.floor for more detail. Math.random:returns a floating-point in a range of [0.0,1.0), refer to Math.random for more detail.

    Obviously, the code Math.floor(Math.random() * 2) will only produce two integer numbers, 0 or 1, which are exactly correspond to the value of BT_NONE and BT_STONE declared in the BlockType enum.

  • Create a new block by the given type:

    1. spawnBlockByType(type: BlockType) {
    2. if (!this.boxPrefab) {
    3. return null;
    4. }
    5. let block: Node|null = null;
    6. switch(type) {
    7. case BlockType.BT_STONE:
    8. block = instantiate(this.boxPrefab);
    9. break;
    10. }
    11. return block;
    12. }

    If the given type is BT_STONE, we create a new block from boxPrefab using instantiate method.

    If the given type is BT_NONE, we just do nothing.

    instantiate: is a built-in method provided by Cocos Creator, it is used for making a copy of an existing node and creating a new instance for a prefab.

Let’s call generateRoad in the start method of GameManager:

  1. start() {
  2. this.generateRoad()
  3. }

You can see the generated map when running the game.

gen-road.png

Camera Follow

In a game that has a movable player, we often let the camera follow the player. As a result, you can see the screen scrolling when the player is moving.

It’s very simple to archive it in Cocos Creator. Just make the following changes.

  1. Select the Canvas node, and uncheck the Align Canvas With Screen property of cc.Canvas component on the Inspector panel.

  2. Drag the Camera node on the Player node, and make it a child node.

setup-scroll.gif

Now, run the game, and you can see the camera is following the player.

scroll.gif

UI layout

UI ( User Interface ) is a very important part of most games. it displays information about the game and allows users to interact with the game systems.

As we mentioned before, In Cocos Creator, all 2D elements should be put directly or indirectly under the Canvas node, or they will not be rendered.

In Cocos Creator, UI is a special collection of 2D elements, they are text, buttons, toggles, etc.

As 2D elements, they also need to be put under the Canvas node.

As we know, UI elements are always fixed on the screen, so we need a fixed camera to render them.

In the previous section, the camera of the Canvas has been changed to follow our Player, it is no longer suitable for UI rendering.

Thus, we need to create a new Canvas for UI.

UICanvas

In the Hierarchy, right lick the scene root and select “Create -> UI Component -> Canvas” in the pop-up menu.

create-ui-canvas.png

Name it “UICanvas”.

ui-canvas.png

Create an empty node named StartMenu under the UICanvas.

Then, create a button node under the StartMenu node, you can find there is a node named ‘Label’ under the button node. Select it and set the String property to ‘Play’.

Now, we have made a ‘Play’ button.

create-start-menu.png

Background & Text

Next, let’s add a background and text to tell users how to play this game.

Create a Sprite node under the ‘StartMenu’ node and name it ‘Bg’.

Assign internal/default_ui/default_panel to the Sprite Frame property of ‘Bg’ node.

Set the value of Type property to SLICED.

Set the Content Size of UITransform to a certain value (e.g. 400,250) .

create-bg.gif

Create a new Label node named ‘Title’ under the ‘StartMenu’ node, and set the properties as below:

  • position: 0,80
  • cc.Label Color: black
  • cc.Label String: Mind Your Step 2D
  • cc.Label Font Size:40

create-title.png

Continue creating some Label nodes to describe the gameplay. Name them ‘Tip’.

create-tip.png

Create a Label node under UICanvas, and name it ‘Step’, to show how many steps the player has taken.

step.png

Now, we have completed the UI layout, let’s write some code to finish the game logic.

Game state

There are 3 states in most games.

  • INIT: game is ready to start
  • PLAYING: game is playing
  • END: game is over, will restart or exit

We can define these states using an enum type as below:

  1. enum GameState{
  2. GS_INIT,
  3. GS_PLAYING,
  4. GS_END,
  5. };

For better readability, let’s put it after the BlockType enum.

Let’s add a setCurState method to GameManger, which will be used to control the state of the game.

The code is as follows.

  1. setCurState (value: GameState) {
  2. switch(value) {
  3. case GameState.GS_INIT:
  4. break;
  5. case GameState.GS_PLAYING:
  6. break;
  7. case GameState.GS_END:
  8. break;
  9. }
  10. }

Add a new method named init to initialize game data.

  1. init() {
  2. //to do something
  3. }

Then, call it in setCurState when the game state is set to GameState.GS_INIT.

  1. setCurState (value: GameState) {
  2. switch(value) {
  3. case GameState.GS_INIT:
  4. this.init();
  5. break;
  6. case GameState.GS_PLAYING:
  7. break;
  8. case GameState.GS_END:
  9. break;
  10. }
  11. }

As designed, the Player only can be controlled by users when the game is running.

So, we make a small change to the input event listener in the PlayerController.

The input event is no longer listening in the start method, instead, we create a new method named setInputActive to handle it. the setInputActive method will be called when needed.

  1. start () {
  2. }
  3. setInputActive(active: boolean) {
  4. if (active) {
  5. input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
  6. } else {
  7. input.off(Input.EventType.MOUSE_UP, this.onMouseUp, this);
  8. }
  9. }

Here, the code of GameManager is like this:

  1. import { _decorator, CCInteger, Component, instantiate, Node, Prefab } from 'cc';
  2. import { BLOCK_SIZE, PlayerController } from './PlayerController';
  3. const { ccclass, property } = _decorator;
  4. enum BlockType{
  5. BT_NONE,
  6. BT_STONE,
  7. };
  8. enum GameState{
  9. GS_INIT,
  10. GS_PLAYING,
  11. GS_END,
  12. };
  13. @ccclass('GameManager')
  14. export class GameManager extends Component {
  15. @property({type: Prefab})
  16. public boxPrefab: Prefab|null = null;
  17. @property({type: CCInteger})
  18. public roadLength: number = 50;
  19. private _road: BlockType[] = [];
  20. start() {
  21. }
  22. init() {
  23. }
  24. setCurState (value: GameState) {
  25. switch(value) {
  26. case GameState.GS_INIT:
  27. this.init();
  28. break;
  29. case GameState.GS_PLAYING:
  30. break;
  31. case GameState.GS_END:
  32. break;
  33. }
  34. }
  35. generateRoad() {
  36. this.node.removeAllChildren();
  37. this._road = [];
  38. // startPos
  39. this._road.push(BlockType.BT_STONE);
  40. for (let i = 1; i < this.roadLength; i++) {
  41. if (this._road[i - 1] === BlockType.BT_NONE) {
  42. this._road.push(BlockType.BT_STONE);
  43. } else {
  44. this._road.push(Math.floor(Math.random() * 2));
  45. }
  46. }
  47. for (let j = 0; j < this._road.length; j++) {
  48. let block: Node | null = this.spawnBlockByType(this._road[j]);
  49. if (block) {
  50. this.node.addChild(block);
  51. block.setPosition(j * BLOCK_SIZE, 0, 0);
  52. }
  53. }
  54. }
  55. spawnBlockByType(type: BlockType) {
  56. if (!this.boxPrefab) {
  57. return null;
  58. }
  59. let block: Node|null = null;
  60. switch(type) {
  61. case BlockType.BT_STONE:
  62. block = instantiate(this.boxPrefab);
  63. break;
  64. }
  65. return block;
  66. }
  67. }

Next, let’s add the logic code.

Game Start

This is not a state, but we must start from here. When the game is launched, the start method of GameManager will be called.

We call setCurState here to initialize the game.

  1. start(){
  2. this.setCurState(GameState.GS_INIT);
  3. }

GS_INIT

In this game state, we should initialize the map, reset the position of the player, show the game UI, etc.

So, we need to add the needed properties to `GameManager.

  1. // References to the startMenu node.
  2. @property({ type: Node })
  3. public startMenu: Node | null = null;
  4. //references to player
  5. @property({ type: PlayerController })
  6. public playerCtrl: PlayerController | null = null;
  7. //references to UICanvas/Steps node.
  8. @property({type: Label})
  9. public stepsLabel: Label|null = null;

In the init method, we add code lines as below:

  1. init() {
  2. //show the start menu
  3. if (this.startMenu) {
  4. this.startMenu.active = true;
  5. }
  6. //generate the map
  7. this.generateRoad();
  8. if (this.playerCtrl) {
  9. //disable input
  10. this.playerCtrl.setInputActive(false);
  11. //reset player data.
  12. this.playerCtrl.node.setPosition(Vec3.ZERO);
  13. this.playerCtrl.reset();
  14. }
  15. }

Handle Button Click Event

Next, let’s implement when users click the ‘Play’ button on the UI, the game starts playing.

Add a new method named onStartButtonClicked to the GameManager class, which is used to handle the click event of ‘Play’ button on the ‘startMenu` node.

In onStartButtonClicked, we just call setCurState to set the game state to GameState.GS_PLAYING.

  1. onStartButtonClicked() {
  2. this.setCurState(GameState.GS_PLAYING);
  3. }

Go back to Cocos Creator, and select the UICanvas/StartMenu/Button node.

On the Inspector panel, type 1 into the input box after Click Events property.

Then drag the GameManager node to the first slot, select GameManager for the second slot, and choose onStartButtonClicked for the third slot.

click-event.gif

GS_PLAYING

After users click the ‘Play’ button, the game is going to this state. We need to:

  • Hide the StartMenu
  • Reset the number of steps
  • Enable user input

The related code in setCurState method is as below:

  1. setCurState(value: GameState) {
  2. switch (value) {
  3. //...
  4. case GameState.GS_PLAYING:
  5. if (this.startMenu) {
  6. this.startMenu.active = false;
  7. }
  8. //reset steps counter to 0
  9. if (this.stepsLabel) {
  10. this.stepsLabel.string = '0';
  11. }
  12. //enable user input after 0.1 second.
  13. setTimeout(() => {
  14. if (this.playerCtrl) {
  15. this.playerCtrl.setInputActive(true);
  16. }
  17. }, 0.1);
  18. break;
  19. //...
  20. }
  21. }

GS_END

We do nothing for now. you can add anything you want to make the game perfect.

Bind properties

Go back to Cocos Creator, and drag the corresponding node to each property for GameManager.

bind-manager.png

Look! We can play it now.

start-game-without-result.gif

Game Over

Next, let’s handle the situation when the player steps on an empty block.

Handle jump end

Add a new property called _curMoveIndex to PlayerController, which is used to record how many steps the player has taken.

  1. private _curMoveIndex: number = 0;

Set it to 0 in the reset method.

  1. reset() {
  2. this._curMoveIndex = 0;
  3. }

In the jumpByStep method, increase it by step.

  1. jumpByStep(step: number) {
  2. if (this._startJump) {
  3. return;
  4. }
  5. this._startJump = true;
  6. this._jumpStep = step;
  7. this._curJumpTime = 0;
  8. this._curJumpSpeed = this._jumpStep * BLOCK_SIZE/ this._jumpTime;
  9. this.getPosition(this._curPos);
  10. Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep* BLOCK_SIZE, 0, 0));
  11. if (this.BodyAnim) {
  12. if (step === 1) {
  13. this.BodyAnim.play('oneStep');
  14. } else if (step === 2) {
  15. this.BodyAnim.play('twoStep');
  16. }
  17. }
  18. this._curMoveIndex += step;
  19. }

Add onOnceJumpEnd to PlayerController to emit an ‘JumpEnd’ event and pass in _curMoveIndex as a parameter.

  1. onOnceJumpEnd() {
  2. this.node.emit('JumpEnd', this._curMoveIndex);
  3. }

Call onOnceJumpEnd in the update of PlayerController when the jump action is over.

  1. update (deltaTime: number) {
  2. if (this._startJump) {
  3. this._curJumpTime += deltaTime;
  4. if (this._curJumpTime > this._jumpTime) {
  5. // end
  6. this.node.setPosition(this._targetPos);
  7. this._startJump = false;
  8. this.onOnceJumpEnd();
  9. } else {
  10. // tween
  11. this.node.getPosition(this._curPos);
  12. this._deltaPos.x = this._curJumpSpeed * deltaTime;
  13. Vec3.add(this._curPos, this._curPos, this._deltaPos);
  14. this.node.setPosition(this._curPos);
  15. }
  16. }
  17. }

Go back to GameManager and add the following code.

  • Add onPlayerJumpEnd method to handle the jump end event.

    1. onPlayerJumpEnd(moveIndex: number) {
    2. }
  • Listen ‘JumpEnd’ event in the start method.

    1. start() {
    2. this.setCurState(GameState.GS_INIT);
    3. this.playerCtrl?.node.on('JumpEnd', this.onPlayerJumpEnd, this);
    4. }

    In Cocos Creator, an event dispatched through the emit of a node can only be listened to by using its on.

  • Add checkResult to check the type of block the player steps on.

    1. checkResult(moveIndex: number) {
    2. if (moveIndex < this.roadLength) {
    3. if (this._road[moveIndex] == BlockType.BT_NONE) { //steps on empty block, reset to init.
    4. this.setCurState(GameState.GS_INIT);
    5. }
    6. } else { //out of map, reset to init.
    7. this.setCurState(GameState.GS_INIT);
    8. }
    9. }
  • Finish the onPlayerJumpEnd method.

    1. onPlayerJumpEnd(moveIndex: number) {
    2. //update steps label.
    3. if (this.stepsLabel) {
    4. this.stepsLabel.string = '' + (moveIndex >= this.roadLength ? this.roadLength : moveIndex);
    5. }
    6. this.checkResult(moveIndex);
    7. }

Layers & Visibility

When playing the game, you may notice the overlapping graphics, this is because the both cameras ( Canvas/Camera, UICanvas/Camera) are rendering all objects.

layer-error.png

In Cocos Creator, a node can only be put in one of the layers, a camera can choose which layers will be rendered by itself.

To solve this problem, we need to allocate the role of the layers and the visibility of cameras.

In this game, we have two types of objects.

  • Scene Object: player, blocks
  • UI Object: windows, buttons, labels

So, we just need to put all of the scene objects to DEFAULT layer and put all of the UI objects to UI_2D layer.

Then, we need to change a little about the visibility of cameras to let the Canvas/Camera only render the objects in DEFAULT layer, the UICanvas/Camera only render the object in UI_2D layer, and everything will be ok.

It’s so clear, now, let’s do it.

DEFAULT

  • Set the layer of Canvas and all its children to DEFAULT

    layer-default.png

  • Set the layer of Box.prefab to DEFAULT

    box-layer.png

    Double-click the left mouse button on the prefab file to enter the prefab editing mode, don’t forget to hit the ‘Save’ button after finishing the modification.

    save-prefab.png

  • Set the Visibility of Canvas/Player/Camera as follows:

    canvas-camera.png

UI_2D

  • Set the Visibility of UICanvas/Camera as follows:

    images/uicanvas-camera.png

    Since the default layer for 2D nodes is UI_2D, we don’t need to set the layer for nodes under UICanvas.

Play the game again, everything is ok now.

after-layer-setting.gif

Summary

Here we come to the end of this tutorial, hope it has been helpful to you.

In the future, you can add more gameplay and features based on this game, such as replacing the Player with an animation role, adding a beautiful background image, adding rhythmic background music and sounds, etc.

If you have any questions, please refer to Get Help and Support.

Full Source Code

PlayerController.ts:

  1. import { _decorator, Component, Vec3, EventMouse, input, Input, Animation } from "cc";
  2. const { ccclass, property } = _decorator;
  3. export const BLOCK_SIZE = 40;
  4. @ccclass("PlayerController")
  5. export class PlayerController extends Component {
  6. @property(Animation)
  7. BodyAnim:Animation = null;
  8. private _startJump: boolean = false;
  9. private _jumpStep: number = 0;
  10. private _curJumpTime: number = 0;
  11. private _jumpTime: number = 0.1;
  12. private _curJumpSpeed: number = 0;
  13. private _curPos: Vec3 = new Vec3();
  14. private _deltaPos: Vec3 = new Vec3(0, 0, 0);
  15. private _targetPos: Vec3 = new Vec3();
  16. private _curMoveIndex: number = 0;
  17. start () {
  18. //input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
  19. }
  20. setInputActive(active: boolean) {
  21. if (active) {
  22. input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
  23. } else {
  24. input.off(Input.EventType.MOUSE_UP, this.onMouseUp, this);
  25. }
  26. }
  27. reset() {
  28. this._curMoveIndex = 0;
  29. }
  30. onMouseUp(event: EventMouse) {
  31. if (event.getButton() === 0) {
  32. this.jumpByStep(1);
  33. } else if (event.getButton() === 2) {
  34. this.jumpByStep(2);
  35. }
  36. }
  37. jumpByStep(step: number) {
  38. if (this._startJump) {
  39. return;
  40. }
  41. this._startJump = true;
  42. this._jumpStep = step;
  43. this._curJumpTime = 0;
  44. // get jump time from animation duration.
  45. const clipName = step == 1? 'oneStep' : 'twoStep';
  46. const state = this.BodyAnim.getState(clipName);
  47. this._jumpTime = state.duration;
  48. this._curJumpSpeed = this._jumpStep * BLOCK_SIZE/ this._jumpTime;
  49. this.node.getPosition(this._curPos);
  50. Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep* BLOCK_SIZE, 0, 0));
  51. if (this.BodyAnim) {
  52. if (step === 1) {
  53. this.BodyAnim.play('oneStep');
  54. } else if (step === 2) {
  55. this.BodyAnim.play('twoStep');
  56. }
  57. }
  58. this._curMoveIndex += step;
  59. }
  60. onOnceJumpEnd() {
  61. this.node.emit('JumpEnd', this._curMoveIndex);
  62. }
  63. update (deltaTime: number) {
  64. if (this._startJump) {
  65. this._curJumpTime += deltaTime;
  66. if (this._curJumpTime > this._jumpTime) {
  67. // end
  68. this.node.setPosition(this._targetPos);
  69. this._startJump = false;
  70. this.onOnceJumpEnd();
  71. } else {
  72. // tween
  73. this.node.getPosition(this._curPos);
  74. this._deltaPos.x = this._curJumpSpeed * deltaTime;
  75. Vec3.add(this._curPos, this._curPos, this._deltaPos);
  76. this.node.setPosition(this._curPos);
  77. }
  78. }
  79. }
  80. }

GameManager.ts:

  1. import { _decorator, CCInteger, Component, instantiate, Label, Node, Prefab, Vec3 } from 'cc';
  2. import { BLOCK_SIZE, PlayerController } from './PlayerController';
  3. const { ccclass, property } = _decorator;
  4. enum BlockType {
  5. BT_NONE,
  6. BT_STONE,
  7. };
  8. enum GameState {
  9. GS_INIT,
  10. GS_PLAYING,
  11. GS_END,
  12. };
  13. @ccclass('GameManager')
  14. export class GameManager extends Component {
  15. @property({ type: Prefab })
  16. public boxPrefab: Prefab | null = null;
  17. @property({ type: CCInteger })
  18. public roadLength: number = 50;
  19. private _road: BlockType[] = [];
  20. @property({ type: Node })
  21. public startMenu: Node | null = null;
  22. @property({ type: PlayerController })
  23. public playerCtrl: PlayerController | null = null;
  24. @property({type: Label})
  25. public stepsLabel: Label|null = null;
  26. start() {
  27. this.setCurState(GameState.GS_INIT);
  28. this.playerCtrl?.node.on('JumpEnd', this.onPlayerJumpEnd, this);
  29. }
  30. init() {
  31. if (this.startMenu) {
  32. this.startMenu.active = true;
  33. }
  34. this.generateRoad();
  35. if (this.playerCtrl) {
  36. this.playerCtrl.setInputActive(false);
  37. this.playerCtrl.node.setPosition(Vec3.ZERO);
  38. this.playerCtrl.reset();
  39. }
  40. }
  41. setCurState(value: GameState) {
  42. switch (value) {
  43. case GameState.GS_INIT:
  44. this.init();
  45. break;
  46. case GameState.GS_PLAYING:
  47. if (this.startMenu) {
  48. this.startMenu.active = false;
  49. }
  50. if (this.stepsLabel) {
  51. this.stepsLabel.string = '0';
  52. }
  53. setTimeout(() => {
  54. if (this.playerCtrl) {
  55. this.playerCtrl.setInputActive(true);
  56. }
  57. }, 0.1);
  58. break;
  59. case GameState.GS_END:
  60. break;
  61. }
  62. }
  63. generateRoad() {
  64. this.node.removeAllChildren();
  65. this._road = [];
  66. // startPos
  67. this._road.push(BlockType.BT_STONE);
  68. for (let i = 1; i < this.roadLength; i++) {
  69. if (this._road[i - 1] === BlockType.BT_NONE) {
  70. this._road.push(BlockType.BT_STONE);
  71. } else {
  72. this._road.push(Math.floor(Math.random() * 2));
  73. }
  74. }
  75. for (let j = 0; j < this._road.length; j++) {
  76. let block: Node | null = this.spawnBlockByType(this._road[j]);
  77. if (block) {
  78. this.node.addChild(block);
  79. block.setPosition(j * BLOCK_SIZE, 0, 0);
  80. }
  81. }
  82. }
  83. spawnBlockByType(type: BlockType) {
  84. if (!this.boxPrefab) {
  85. return null;
  86. }
  87. let block: Node | null = null;
  88. switch (type) {
  89. case BlockType.BT_STONE:
  90. block = instantiate(this.boxPrefab);
  91. break;
  92. }
  93. return block;
  94. }
  95. onStartButtonClicked() {
  96. this.setCurState(GameState.GS_PLAYING);
  97. }
  98. checkResult(moveIndex: number) {
  99. if (moveIndex < this.roadLength) {
  100. if (this._road[moveIndex] == BlockType.BT_NONE) {
  101. this.setCurState(GameState.GS_INIT);
  102. }
  103. } else {
  104. this.setCurState(GameState.GS_INIT);
  105. }
  106. }
  107. onPlayerJumpEnd(moveIndex: number) {
  108. if (this.stepsLabel) {
  109. this.stepsLabel.string = '' + (moveIndex >= this.roadLength ? this.roadLength : moveIndex);
  110. }
  111. this.checkResult(moveIndex);
  112. }
  113. }