Sweshi's Tutorials

Cocoos Creator 3D Runner Tutorial

Working witht the road

For such a game we can achieve the movement effect in two ways, we can create the node and the environment and make either the environment move towards the player or make the player move towards the environment. Depending on the amount of things in the environment it could be costly in terms of performance to choose either method. For a game with very few objects in the scene, we can move those objects towards the player. A space shooter game of this nature would work well. The more items are added to the scene, the more the performance cost in moving each one so we could opt for having stationery objects in the environment and move the player and camera instead. In most cases, this will be the easier option. In our case, we will try both methods. We will start by moving the environment towards the player. We will start off with making the road move towards the player to achieve a motion effect for the player running. To do this first create a typescript file in the “Scripts” folder that we created earlier. Right click the Scripts folder->Create->TypeScript->NewComponent. Name the new script as “RoadScript”. The code in the script should be as shown below.

Cocos Creator Tutorial: creating the road script
Code for the road
import { _decorator, Component, Node,Vec3 } from 'cc'; const { ccclass, property } = _decorator; @ccclass('RoadScript') export class RoadScript extends Component { update(deltaTime: number) { const currentPosition = this.node.position; //Move the character to the left by 0.1 const moveAmount = new Vec3(0, 0, 0.1); // Add the move amount to the current position Vec3.add(currentPosition, currentPosition, moveAmount); // Update the position of the node this.node.setPosition(currentPosition); } }

The code is written in the update method because we need it to run per frame. We are simply getting the position of the road through the variable currentPosition. We then set a movement amount of 0.1 on the Z axis which is a slight movement towards the player. We add the current position of the road to the moveAmount setting the result to the currentPosition variable. We then set the road to this new position we get from the addition. If you want the road to move faster or slower, you can increase or reduce from 0.1.

Cocos Creator Tutorial:roadScript

You can then click on the road in the Node hierarchy and then go to the inspector panel. Click on the “Add Component” button at the bottom of the inspector panel and then search for the “RoadScript” just as it was named. Click on it and it will be added to the road Node. If you run the simulator now, the road should be moving towards the player and it looks like the player has run successfully.

Cocos Creator Tutorial: adding the script to the road