Advanced: Add Light, Shadow and Skeleton Animation

In this section, we will show you how to use third-part assets such as animation, etc to complete the game prototype we have made in Quick Start: Make Your First 3D Game

Lighting and Shadows

Lighting and shadows are important rendering features that describe the game. With light sources and shadows, we can simulate a more realistic game world, providing better immersion and empathy.

Next, we add a simple shadow to the character.

Turn on shadows

  1. Click the top Scene node in the Hierarchy panel, then in the Inspector panel check Enabled in shadows and modify the Distance and Normal properties to:

    planar shadows

  2. Click on the Body node under the Player node and set ShadowCastingMode to ON in the cc.MeshRenderer component.

    model shadow

At this point, you will see a shadow sheet in the Scene Editor. The preview will show that the shadow is not visible because it is directly behind the model, covered by the capsule.

player shadow

Adjusting lighting

By default, a Main Light node with cc.DirectionalLight component is added when creating a new scene. So to make the shadows appear in a different position, we can adjust the direction of this light. Click in the Hierarchy panel to select the Main Light node and adjust the Rotation property to (-10, 17, 0).

main light

The shadow effect can be seen by clicking on the preview at

player shadow preview

Adding a protagonist model

Importing model resources

Importing models, materials, animations and other resources from the original sources is not the focus of this basic tutorial, so we will directly use the resources that have been imported into the project. Put project (GitHub in the assets directory and copy the cocos folder to the assets directory of your own project.

Adding to the scene

A Prefab named Cocos is already included in the Cocos file. Drag it to the Body node under the Player node in the Hierarchy panel as a child node of the Body node.

add cocos prefab

Also, remove the original capsule model from the Inspector panel:

remove capsule

You can add a Spotlight under the Cocos node to highlight its shiny head.

add cocos light

Add jump animation

Now the preview shows that the main character will have a standby animation initially, but it will look very inconsistent to use this standby animation when jumping, so we can change it to a jump animation during jumping. Add a variable to the PlayerController.ts class that references the model animation:

  1. @property({type: SkeletalAnimation})
  2. public CocosAnim: SkeletalAnimation|null = null;

Also, since we have changed the protagonist from a capsule body to a character model, we can discard the animation previously created for the capsule body and comment on the relevant code as follows:

  1. // @property({type: Animation})
  2. // public BodyAnim: Animation|null = null;
  3. jumpByStep(step: number) {
  4. // ...
  5. // if (this.BodyAnim) {
  6. // if (step === 1) {
  7. // this.BodyAnim.play('oneStep');
  8. // } else if (step === 2) {
  9. // this.BodyAnim.play('twoStep');
  10. // }
  11. // }
  12. }

Then in the Hierarchy panel drag and drop the Cocos node into the CocosAnim property box of the Player node:

assign cocos prefab

Play the jump animation in the jumpByStep function of the PlayerController script:

  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 / this._jumpTime;
  9. this.node.getPosition(this._curPos);
  10. Vec3.add(this._targetPos, this._curPos, new Vec3(this._jumpStep, 0, 0));
  11. if (this.CocosAnim) {
  12. this.CocosAnim.getState('cocos_anim_jump').speed = 3.5; // Jump animation time is relatively long, here to speed up the playback
  13. this.CocosAnim.play('cocos_anim_jump'); // Play jump animation
  14. }
  15. // if (this.BodyAnim) {
  16. // if (step === 1) {
  17. // this.BodyAnim.play('oneStep');
  18. // } else if (step === 2) {
  19. // this.BodyAnim.play('twoStep');
  20. // }
  21. // }
  22. this._curMoveIndex += step;
  23. }

Here _jumpStep time is 0.3 seconds, if the animation length and _jumpStep don’t match, it may cause the following problem:

  • The animation transition is not smooth when the animation is not finished yet
  • or the animation is finished but the jump time is not yet up, resulting in slippage

One way to handle this is to recalculate the speed of the animation directly from the length of the animation clip and _jumpStep instead of using a constant: _jumpStep:

  1. var state = this.CocosAnim.getState('cocos_anim_jump');
  2. state.speed = state.duration/this._jumpTime;

Developers can try it themselves, or manually modify _jumpStep and speed to the right values to control the game’s pace.

In the OnceJumpEnd function of the PlayerController script, make the main character standby and play the standby animation.

  1. onOnceJumpEnd() {
  2. if (this.CocosAnim) {
  3. this.CocosAnim.play('cocos_anim_idle');
  4. }
  5. this.node.emit('JumpEnd', this._curMoveIndex);
  6. }

Note: onOnceJumpEnd will be triggered when the jump is completed, see the update function in PlayerController.ts for details.

The preview effect is as follows:

cocos play

Final Code

PlayerController.ts

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

GameManager.ts

  1. import { _decorator, Component, Prefab, instantiate, Node, Label, CCInteger, Vec3 } from 'cc';
  2. import { PlayerController } from "./PlayerController";
  3. const { ccclass, property } = _decorator;
  4. // The runway type, pit (BT_NONE) or solid road (BT_STONE)
  5. enum BlockType{
  6. BT_NONE,
  7. BT_STONE,
  8. };
  9. enum GameState{
  10. GS_INIT,
  11. GS_PLAYING,
  12. GS_END,
  13. };
  14. @ccclass("GameManager")
  15. export class GameManager extends Component {
  16. // The runway prefab
  17. @property({type: Prefab})
  18. public cubePrfb: Prefab | null = null;
  19. // Length of the road
  20. @property({type: CCInteger})
  21. public roadLength: Number = 50;
  22. private _road: BlockType[] = [];
  23. // Node of the start menu
  24. @property({type: Node})
  25. public startMenu: Node | null = null;
  26. // The reference of the PlayerController instance on the Player node
  27. @property({type: PlayerController})
  28. public playerCtrl: PlayerController | null = null;
  29. // Label to display the step
  30. @property({type: Label})
  31. public stepsLabel: Label | null = null!;
  32. start () {
  33. this.curState = GameState.GS_INIT;
  34. this.playerCtrl?.node.on('JumpEnd', this.onPlayerJumpEnd, this);
  35. }
  36. init() {
  37. // Active the start menu
  38. if (this.startMenu) {
  39. this.startMenu.active = true;
  40. }
  41. // Generate the runway
  42. this.generateRoad();
  43. if(this.playerCtrl){
  44. // Disable user input
  45. this.playerCtrl.setInputActive(false);
  46. // Reset the player's position
  47. this.playerCtrl.node.setPosition(Vec3.ZERO);
  48. // Reset the steps
  49. this.playerCtrl.reset();
  50. }
  51. }
  52. set curState (value: GameState) {
  53. switch(value) {
  54. case GameState.GS_INIT:
  55. this.init();
  56. break;
  57. case GameState.GS_PLAYING:
  58. if (this.startMenu) {
  59. this.startMenu.active = false;
  60. }
  61. if (this.stepsLabel) {
  62. this.stepsLabel.string = '0'; // Reset the number of steps to 0
  63. }
  64. // What happens is that the character already starts moving at the moment the game starts
  65. // Therefore, a delay is needed here
  66. setTimeout(() => {
  67. if (this.playerCtrl) {
  68. this.playerCtrl.setInputActive(true);
  69. }
  70. }, 0.1);
  71. break;
  72. case GameState.GS_END:
  73. break;
  74. }
  75. }
  76. generateRoad() {
  77. // Prevent the track from being the old track when the game is restarted
  78. // Therefore, the old track needs to be removed and the old track data cleared
  79. this.node.removeAllChildren();
  80. this._road = [];
  81. // Make sure that the character is standing on the real road when the game is running
  82. this._road.push(BlockType.BT_STONE);
  83. // Determine the type of track for each frame
  84. for (let i = 1; i < this.roadLength; i++) {
  85. // If the last track is a pit, then this frame must not be a pit
  86. if (this._road[i-1] === BlockType.BT_NONE) {
  87. this._road.push(BlockType.BT_STONE);
  88. } else {
  89. this._road.push(Math.floor(Math.random() * 2));
  90. }
  91. }
  92. // Generate tracks based on track type
  93. let linkedBlocks = 0;
  94. for (let j = 0; j < this._road.length; j++) {
  95. if(this._road[j]) {
  96. ++linkedBlocks;
  97. }
  98. if(this._road[j] == 0) {
  99. if(linkedBlocks > 0) {
  100. this.spawnBlockByCount(j - 1, linkedBlocks);
  101. linkedBlocks = 0;
  102. }
  103. }
  104. if(this._road.length == j + 1) {
  105. if(linkedBlocks > 0) {
  106. this.spawnBlockByCount(j, linkedBlocks);
  107. linkedBlocks = 0;
  108. }
  109. }
  110. }
  111. }
  112. spawnBlockByCount(lastPos: number, count: number) {
  113. let block: Node|null = this.spawnBlockByType(BlockType.BT_STONE);
  114. if(block) {
  115. this.node.addChild(block);
  116. block?.setScale(count, 1, 1);
  117. block?.setPosition(lastPos - (count - 1) * 0.5, -1.5, 0);
  118. }
  119. }
  120. spawnBlockByType(type: BlockType) {
  121. if (!this.cubePrfb) {
  122. return null;
  123. }
  124. let block: Node|null = null;
  125. switch(type) {
  126. case BlockType.BT_STONE:
  127. block = instantiate(this.cubePrfb);
  128. break;
  129. }
  130. return block;
  131. }
  132. onStartButtonClicked() {
  133. // To start the game by clicking the Play button
  134. this.curState = GameState.GS_PLAYING;
  135. }
  136. checkResult(moveIndex: number) {
  137. if (moveIndex < this.roadLength) {
  138. // Jumped on the pit
  139. if (this._road[moveIndex] == BlockType.BT_NONE) {
  140. this.curState = GameState.GS_INIT;
  141. }
  142. } else { // Jumped over the maximum length
  143. this.curState = GameState.GS_INIT;
  144. }
  145. }
  146. onPlayerJumpEnd(moveIndex: number) {
  147. if (this.stepsLabel) {
  148. // Because in the last step there may be a jump with a large pace, but at this time, whether the jump is a large pace or a small pace should not increase the score more
  149. this.stepsLabel.string = '' + (moveIndex >= this.roadLength ? this.roadLength : moveIndex);
  150. }
  151. // Check the type of the currently falling road and get the result
  152. this.checkResult(moveIndex);
  153. }
  154. // update (deltaTime: number) {
  155. // // Your update function goes here.
  156. // }
  157. }

Conclusion

Congratulations on completing your first game made with Cocos Creator! You can download the full project at GitHub - Mind-Your-Step-3D. We hope this quick start tutorial will help you understand the basic concepts and workflow of the Cocos Creator game development process. If you are not interested in writing and learning to script, you can also copy the script directly from the finished project.

Next, you can continue to improve all aspects of the game, here are some recommended improvements:

  • Add difficulty to the game, when the character stays in the same place for 1 second it is considered a failure
  • Change the runway to infinite, dynamically delete the runway that has been run and extend the runway behind.
  • Add game sound effects
  • Add an end menu for the game, count the number of jumps and the time spent by the player
  • Replace characters and runways with more beautiful resources
  • Add some pickup items to guide the player to “make mistakes”
  • Add some particle effects, such as trailing when the character is moving, dust when it hits the ground
  • Add two buttons for touchscreen devices instead of left and right mouse buttons

In addition, if you want to publish your finished game to the server and share it with your friends, you can read the Cross-Platform Game Publishing section.