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



                          
  1. /*!
  2. @short Main
  3. */
  4. class Main
  5. {
  6. // How many times do we want to duplicate the cube ?
  7. cube_amount = 500
  8.  
  9. /*!
  10. @short OnSetup
  11. Called when the scene is about to be setup.
  12. */
  13. function OnSetup(scene)
  14. {
  15. local base_item, // original cube
  16. new_item // copy
  17.  
  18. base_item = SceneFindItem(scene, "cube_00")
  19.  
  20. local n
  21. for(n = 0; n < cube_amount; n++)
  22. {
  23. // Create a copy of the base item ('Cube_00' in the current scene).
  24. new_item = SceneDuplicateItem(scene, base_item)
  25.  
  26. // Move it to a random position
  27. // Use the macro Mtr() to tell the engine you work in Meter.
  28. ItemSetPosition(new_item, Vector(Mtr(Rand(-25,25)), Mtr(0), Mtr(Rand(-25,25))))
  29.  
  30. local scale_factor, rotation_y
  31.  
  32. // Scale doesn't need any unit
  33. // Angles are in Rad in the engine,
  34. // hence you need a macro to convert them from Deg.
  35. scale_factor = Rand(0.05, 0.5)
  36. rotation_y = DegreeToRadian(Rand(0.0, 90.0))
  37.  
  38. ItemSetScale(new_item, Vector(scale_factor, scale_factor, scale_factor))
  39. ItemSetRotation(new_item, Vector(0, rotation_y, 0))
  40. }
  41. }
  42. }