Sweshi's Tutorials

Cocoos Creator 3D Runner Tutorial

Creating the Player Script in Cocos Creator and using keyboard event listeners

In the assets section, create a new folder called scripts. To do this, right click the assets folder -> Create->Folder. Name the folder “Scripts”.

Cocos Creator Tutorial: creating the script folder in the assets

We will then create a TypeScript file named PlayerScript. To do this, right click the scripts folder that you just created ->create->TypeScript->NewComponent. Name the script as PlayerScript. Open the Script with a code editor such as visual studio code and add the following code.

Cocos Creator Tutorial: creating the cocos creator typescript file in the scripts folder
Code for the player script
import { _decorator, Component, Node,Vec3, EventKeyboard, KeyCode, input, Input, Event } from 'cc'; const { ccclass, property } = _decorator; @ccclass('PlayerScript') export class PlayerScript extends Component { //store the status of the right arrow key being pressed. //Store true if the right arrow key is pressed private isRightKeyPressed: boolean = false; //store the status of the left arrow key being pressed. // Store true if the left arrow key is pressed private isLeftKeyPressed: boolean = false; onLoad(){ //setting up the keyboard event listeners //listening for key presses input.on(Input.EventType.KEY_DOWN,this.onKeyDown,this); //listening for key releases input.on(Input.EventType.KEY_UP,this.onKeyUp,this); } onDestroy(){ //switching off the keyboard event listener when the game closes input.off(Input.EventType.KEY_DOWN,this.onKeyDown,this); input.off(Input.EventType.KEY_UP,this.onKeyUp,this); } //what to do when a key is pressed onKeyDown(event:EventKeyboard){ //get the keyboard event switch(event.keyCode){ //get the key that was pressed case KeyCode.ARROW_LEFT: //check if the left arrow key was pressed //log that the left arrow key was pressed console.log("pressed the left key"); //set the status to true for the left key being pressed this.isLeftKeyPressed = true; break; //check if the right arrow key is bring pressed case KeyCode.ARROW_RIGHT: console.log("pressed the right key"); //set the status to true for the right key being pressed this.isRightKeyPressed = true; break; } } //what to do when we stop pressing the arrow keys (when we release the keys) onKeyUp(event:EventKeyboard){ //Store the default rotation of the player const targetRotation = new Vec3(0, 180, 0); switch(event.keyCode){ //check if the left arrow key is nolonger being pressed case KeyCode.ARROW_LEFT: console.log("released the left key"); //set the status to false for the left key being pressed this.isLeftKeyPressed = false; //set the player rotation back to the default of 180 this.node.eulerAngles = targetRotation; break; //check if the right arrow key is nologer being pressed case KeyCode.ARROW_RIGHT: console.log("released the right key"); //set the player rotation back to the default of 180 this.node.eulerAngles = targetRotation; //set the status to false for the right key being pressed this.isRightKeyPressed = false; break; } } update(deltaTime: number) { //check if the right arrow key is being pressed and //if the player is not too far on the right i.e beyond 4.5 if(this.isRightKeyPressed && this.node.position.x<4.5){ //get the current position of the player const currentPosition = this.node.position; // Move the character to the right by 0.1 const moveAmount = new Vec3(0.1, 0, 0); // Add the move amount to the current position Vec3.add(currentPosition, currentPosition, moveAmount); // Update the position of the node this.node.setPosition(currentPosition); //set rotation to 135 so that the player slightly faces the right const targetRotation = new Vec3(0, 135, 0); this.node.eulerAngles = targetRotation; } //check if the left arrow key is being pressed and //if the player is not too far on the left i.e beyond -4.5 if(this.isLeftKeyPressed && this.node.position.x>-4.5){ const currentPosition = this.node.position; //Move the character to the left by 0.1 const moveAmount = new Vec3(-0.1, 0, 0); // Add the move amount to the current position Vec3.add(currentPosition, currentPosition, moveAmount); // Update the position of the node this.node.setPosition(currentPosition); //set rotation to 225 so that the player slightly faces the left const targetRotation = new Vec3(0, 225, 0); this.node.eulerAngles = targetRotation; } } }

I have tried to explain the lines of code using the comments but I will summarise everything going on again in this section.

Cocos Creator Tutorial: creating the cocos creator booleans

We create variables that have to store the state of the left and right arrow keys. We have Boolean variables for the left and right keys being pressed. By default, they are at false because neither key is being pressed. Later in the code, when the right arrow key is pressed, the first variable will be set to true then when released back to false. This will also happen for the left arrow key.

Cocos Creator Tutorial: switching on the cocos creator keyboard event listeners

In the onload, we switch on the keyboard event listener so that we run the “onKeyDown” function whenever a button is pressed and the “onKeyUp” function when a key is released.

Cocos Creator Tutorial: switching off the cocos creator keyboard event listeners

We also switch off the keyboard event listeners when the game is closing so that key presses and releases are no longer picked up by the game.

Cocos Creator Tutorial: checking if the keyboard left or right arrow keys are pressed in cocos creator

Because the keyboard has so many keys and the event listener picks up every key press and release, we need to filter the key presses so that we only do something when the left or right arrow keys are pressed. We use the switch to filter the keys that are pressed. If the arrow left key is pressed, we change the state of the Boolean “isLeftKeyPressed” to true. By doing this we store the fact that the left arrow key is pressed which is useful later when moving the player. We also do the same when the right arrow key is pressed.

Cocos Creator Tutorial:checking the keys are released in cocos creator

When the arrow keys are released, we need to set the player rotation so that the player is facing the front again after they are done moving. So, we set the rotation angle to 180 on the y axis. We also set the Booleans to false so that the we record that the arrow keys are nolonger being pressed.

Cocos Creator Tutorial: moving the player to the right in cocos creator

To move the player to the right or left, we go into the update function because it runs in every frame so we can make small adjustments per frame such as moving the character. In this screenshot we use the if statement to first check if the right arrow key is being pressed and then check if the player’s position is not beyond 4.5 on the x axis. If both these conditions are true, we can then get the position of the character and set the character to move to the right side by increasing the x position from 0 to 0.1. we then add the current position to this new “moveAmount” that creates the new position. We finally set the position of the player to this new calculated position. This will move the player if you press the right arrow key but will stop if the player gets to the end of the road. Of course, you can change the value of 0.1 to anything that you feel plays correctly. We also change the rotation of the player so that when they are moving to the right, they are also facing the right. To do this, we change the rotation of the player to 135 from the 180 which was the default set on the y axis. The 180 was set to make the player face the front and the 135 will make the player face slightly towards the right.

Cocos Creator Tutorial: moving the player to the left in cocos creator

To move the player to the left, we basically do the same thing but switch to the left side. The player should not move beyond -4.5, and rotate to 225 on the y axis.

Cocos Creator Tutorial: adding the script to the player.png

Click on the cocos character in the node hierarchy. Once done, go to the inspector and click on the “Add Component” button at the bottom right side of the window. Search for “PlayerScript” and this will bring the TypeScript file we just created. Select it and it will be added to the player. This will enable our code to work on the player. Save the project.

Cocos Creator Tutorial: verify that you are able to move

Verify that you are able to move the player to the left or the right of the screen by pressing the left and right arrow keys. Make sure that the player is not running beyond the road.