Script - Duplicate an Item at Runtime
This tutorial will detail how to duplicate an item several times, during the setup of a scene.
Description
The tutorial will show how to perform this different tasks in a script :
- Find an item by its name in the scene.
- Duplicate an item and keep the handler of the copy.
- Change the position, scale and rotation of an item.
- Using the Rand() function, and various units / conversion macros.
You will notice in the video how the automatic completion provides suggestion among the API functions in order to assist the developer. This is one of the main benefits of using the internal script editor of GameStart.
The project & files used in the tutorial can be found attached at the bottom of the page. A copy of the script can be found below.
Script used in this tutorial
-
/*!
-
@short Main
-
*/
-
class Main
-
{
-
// How many times do we want to duplicate the cube ?
-
cube_amount = 500
-
-
/*!
-
@short OnSetup
-
Called when the scene is about to be setup.
-
*/
-
function OnSetup(scene)
-
{
-
local base_item, // original cube
-
new_item // copy
-
-
base_item = SceneFindItem(scene, "cube_00")
-
-
local n
-
for(n = 0; n < cube_amount; n++)
-
{
-
// Create a copy of the base item ('Cube_00' in the current scene).
-
new_item = SceneDuplicateItem(scene, base_item)
-
-
// Move it to a random position
-
// Use the macro Mtr() to tell the engine you work in Meter.
-
ItemSetPosition(new_item, Vector(Mtr(Rand(-25,25)), Mtr(0), Mtr(Rand(-25,25))))
-
-
local scale_factor, rotation_y
-
-
// Scale doesn't need any unit
-
// Angles are in Rad in the engine,
-
// hence you need a macro to convert them from Deg.
-
scale_factor = Rand(0.05, 0.5)
-
rotation_y = DegreeToRadian(Rand(0.0, 90.0))
-
-
ItemSetScale(new_item, Vector(scale_factor, scale_factor, scale_factor))
-
ItemSetRotation(new_item, Vector(0, rotation_y, 0))
-
}
-
}
-
}