moving_platform.lua 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. -- Note: the following table must be global and uniquely named.
  2. UnitsMovingPlatformMovingPlatform = UnitsMovingPlatformMovingPlatform or {
  3. data = {}
  4. }
  5. local data = UnitsMovingPlatformMovingPlatform.data
  6. function UnitsMovingPlatformMovingPlatform.spawned(world, units)
  7. if data[world] == nil then
  8. data[world] = {}
  9. end
  10. local world_data = data[world]
  11. for _, unit in pairs(units) do
  12. -- Store instance-specific data.
  13. if world_data[unit] == nil then
  14. world_data[unit] = { zmin = 0.75, zmax = 7.75, zvel = 2, twait = 1.0, tcur = 0 }
  15. end
  16. end
  17. end
  18. function UnitsMovingPlatformMovingPlatform.update(world, dt)
  19. local world_data = data[world]
  20. local scene_graph = World.scene_graph(world)
  21. -- Moving platform.
  22. for unit, unit_data in pairs(world_data) do
  23. local platform = SceneGraph.instance(scene_graph, unit)
  24. local platform_pos = SceneGraph.local_position(scene_graph, platform)
  25. if unit_data.tcur == 0 and (platform_pos.z >= unit_data.zmax or platform_pos.z <= unit_data.zmin) then
  26. unit_data.zvel = -unit_data.zvel
  27. unit_data.tcur = unit_data.twait
  28. end
  29. if unit_data.tcur <= 0 then
  30. local new_position = platform_pos + Vector3(0, 0, unit_data.zvel) * dt
  31. new_position.z = math.max(unit_data.zmin, math.min(unit_data.zmax, new_position.z))
  32. SceneGraph.set_local_position(scene_graph, platform, new_position)
  33. unit_data.tcur = 0
  34. else
  35. unit_data.tcur = unit_data.tcur - dt
  36. end
  37. end
  38. end
  39. function UnitsMovingPlatformMovingPlatform.unspawned(world, units)
  40. local world_data = data[world]
  41. -- Cleanup.
  42. for _, unit in pairs(units) do
  43. if world_data[unit] then
  44. world_data[unit] = nil
  45. end
  46. end
  47. end
  48. return UnitsMovingPlatformMovingPlatform