Sweshi's Tutorials

Cocoos Creator 3D Runner Tutorial

Generating coins at random posistions

We now need the coins to be generated over the whole road. To do this, we first need to create a prefab of the coin we have.Drag the coin from the Node Hierarchy to the prefabs folder in the assets section as shown in the figure below. The GameManager will be responsible for generating the coins so open the GameManager Script.

Cocos Creator Tutorial:creating the coin prefab

Add this line of code under the roadPrefab we created earlier. Save the project and go to the editor so that we can add the coin prefab.

Cocos Creator Tutorial:GameManager coin prefab

Click on the Game Manager, in the inspector a coin prefab empty slot will be present because of the property we just added. Drag the coin prefab from the prefabs section to the coin prefab section on the inspector. Go back to the GameManager TypeScript file.

Cocos Creator Tutorial: coin prefab added to game manager

Create a new function inside the GameManager script. This function will be getting an array of numbers and then picking a random number from them. It will then return the selected number.

Cocos Creator Tutorial: getRandomNumber function

Inside the for loop where we were generating the road, add a new section as highlighted in the screenshot above. The code works just like the one for generating the road, the main difference is that I added a section with 3 numbers. The array is called options and has 3.5, 0 and -3.5. This is then sent to the getRandomNumber function that was just created. The function returns one of these numbers. Whatever number is returned is then used as the value for the x axis when generating the coin. This ensures that coins can be generated in the middle, left or right side of the screen.

Cocos Creator Tutorial: generating the coins randomly

If we simulate the game now, the coins will be generated in one of three sections for every 10 spaces or for each block section.

Cocos Creator Tutorial: simulating the game

Open the coinScript file and add the line “this.nod.destroy()” in the onCollisionEnter function. This will make sure that when the player collides with the coin, the coin will be removed from the screen. In the next section we will add code that can track how many coins have been collected.

Cocos Creator Tutorial: 75 coinScript