11_Physics.lua 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. -- Physics example.
  2. -- This sample demonstrates:
  3. -- - Creating both static and moving physics objects to a scene
  4. -- - Displaying physics debug geometry
  5. -- - Using the Skybox component for setting up an unmoving sky
  6. -- - Saving a scene to a file and loading it to restore a previous state
  7. require "LuaScripts/Utilities/Sample"
  8. function Start()
  9. -- Execute the common startup for samples
  10. SampleStart()
  11. -- Create the scene content
  12. CreateScene()
  13. -- Create the UI content
  14. CreateInstructions()
  15. -- Setup the viewport for displaying the scene
  16. SetupViewport()
  17. -- Hook up to the frame update and render post-update events
  18. SubscribeToEvents()
  19. end
  20. function CreateScene()
  21. scene_ = Scene()
  22. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  23. -- Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  24. -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  25. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry
  26. scene_:CreateComponent("Octree")
  27. scene_:CreateComponent("PhysicsWorld")
  28. scene_:CreateComponent("DebugRenderer")
  29. -- Create a Zone component for ambient lighting & fog control
  30. local zoneNode = scene_:CreateChild("Zone")
  31. local zone = zoneNode:CreateComponent("Zone")
  32. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  33. zone.ambientColor = Color(0.15, 0.15, 0.15)
  34. zone.fogColor = Color(1.0, 1.0, 1.0)
  35. zone.fogStart = 300.0
  36. zone.fogEnd = 500.0
  37. -- Create a directional light to the world. Enable cascaded shadows on it
  38. local lightNode = scene_:CreateChild("DirectionalLight")
  39. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  40. local light = lightNode:CreateComponent("Light")
  41. light.lightType = LIGHT_DIRECTIONAL
  42. light.castShadows = true
  43. light.shadowBias = BiasParameters(0.00025, 0.5)
  44. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  45. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  46. -- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  47. -- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  48. -- generate the necessary 3D texture coordinates for cube mapping
  49. local skyNode = scene_:CreateChild("Sky")
  50. skyNode:SetScale(500.0) -- The scale actually does not matter
  51. local skybox = skyNode:CreateComponent("Skybox")
  52. skybox.model = cache:GetResource("Model", "Models/Box.mdl")
  53. skybox.material = cache:GetResource("Material", "Materials/Skybox.xml")
  54. -- Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
  55. local floorNode = scene_:CreateChild("Floor")
  56. floorNode.position = Vector3(0.0, -0.5, 0.0)
  57. floorNode.scale = Vector3(1000.0, 1.0, 1000.0)
  58. local floorObject = floorNode:CreateComponent("StaticModel")
  59. floorObject.model = cache:GetResource("Model", "Models/Box.mdl")
  60. floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  61. -- Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
  62. -- parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
  63. -- in the physics simulation
  64. local body = floorNode:CreateComponent("RigidBody")
  65. local shape = floorNode:CreateComponent("CollisionShape")
  66. -- Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
  67. -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  68. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  69. -- Create a pyramid of movable physics objects
  70. for y = 0, 7 do
  71. for x = -y, y do
  72. local boxNode = scene_:CreateChild("Box")
  73. boxNode.position = Vector3(x, -y + 8.0, 0.0)
  74. local boxObject = boxNode:CreateComponent("StaticModel")
  75. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  76. boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
  77. boxObject.castShadows = true
  78. -- Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
  79. -- and also adjust friction. The actual mass is not important only the mass ratios between colliding
  80. -- objects are significant
  81. local body = boxNode:CreateComponent("RigidBody")
  82. body.mass = 1.0
  83. body.friction = 0.75
  84. local shape = boxNode:CreateComponent("CollisionShape")
  85. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  86. end
  87. end
  88. -- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  89. -- the scene, because we want it to be unaffected by scene load / save
  90. cameraNode = Node()
  91. local camera = cameraNode:CreateComponent("Camera")
  92. camera.farClip = 500.0
  93. -- Set an initial position for the camera scene node above the floor
  94. cameraNode.position = Vector3(0.0, 5.0, -20.0)
  95. end
  96. function CreateInstructions()
  97. -- Construct new Text object, set string to display and font to use
  98. local instructionText = ui.root:CreateChild("Text")
  99. instructionText:SetText("Use WASD keys and mouse to move\n"..
  100. "LMB to spawn physics objects\n"..
  101. "F5 to save scene, F7 to load\n"..
  102. "Space to toggle physics debug geometry")
  103. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  104. -- The text has multiple rows. Center them in relation to each other
  105. instructionText.textAlignment = HA_CENTER
  106. -- Position the text relative to the screen center
  107. instructionText.horizontalAlignment = HA_CENTER
  108. instructionText.verticalAlignment = VA_CENTER
  109. instructionText:SetPosition(0, ui.root.height / 4)
  110. end
  111. function SetupViewport()
  112. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  113. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  114. renderer:SetViewport(0, viewport)
  115. end
  116. function SubscribeToEvents()
  117. -- Subscribe HandleUpdate() function for processing update events
  118. SubscribeToEvent("Update", "HandleUpdate")
  119. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  120. -- debug geometry
  121. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  122. end
  123. function MoveCamera(timeStep)
  124. -- Do not move if the UI has a focused element (the console)
  125. if ui.focusElement ~= nil then
  126. return
  127. end
  128. -- Movement speed as world units per second
  129. local MOVE_SPEED = 20.0
  130. -- Mouse sensitivity as degrees per pixel
  131. local MOUSE_SENSITIVITY = 0.1
  132. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  133. local mouseMove = input.mouseMove
  134. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  135. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  136. pitch = Clamp(pitch, -90.0, 90.0)
  137. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  138. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  139. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  140. if input:GetKeyDown(KEY_W) then
  141. cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  142. end
  143. if input:GetKeyDown(KEY_S) then
  144. cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  145. end
  146. if input:GetKeyDown(KEY_A) then
  147. cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  148. end
  149. if input:GetKeyDown(KEY_D) then
  150. cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  151. end
  152. -- "Shoot" a physics object with left mousebutton
  153. if input:GetMouseButtonPress(MOUSEB_LEFT) then
  154. SpawnObject()
  155. end
  156. -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
  157. -- directory
  158. if input:GetKeyPress(KEY_F5) then
  159. scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
  160. end
  161. if input:GetKeyPress(KEY_F7) then
  162. scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
  163. end
  164. -- Toggle debug geometry with space
  165. if input:GetKeyPress(KEY_SPACE) then
  166. drawDebug = not drawDebug
  167. end
  168. end
  169. function SpawnObject()
  170. -- Create a smaller box at camera position
  171. local boxNode = scene_:CreateChild("SmallBox")
  172. boxNode.position = cameraNode.position
  173. boxNode.rotation = cameraNode.rotation
  174. boxNode:SetScale(0.25)
  175. local boxObject = boxNode:CreateComponent("StaticModel")
  176. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  177. boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
  178. boxObject.castShadows = true
  179. -- Create physics components, use a smaller mass also
  180. local body = boxNode:CreateComponent("RigidBody")
  181. body.mass = 0.25
  182. body.friction = 0.75
  183. local shape = boxNode:CreateComponent("CollisionShape")
  184. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  185. local OBJECT_VELOCITY = 10.0
  186. -- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  187. -- to overcome gravity better
  188. body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY
  189. end
  190. function HandleUpdate(eventType, eventData)
  191. -- Take the frame time step, which is stored as a float
  192. local timeStep = eventData:GetFloat("TimeStep")
  193. -- Move the camera, scale movement with time step
  194. MoveCamera(timeStep)
  195. end
  196. function HandlePostRenderUpdate(eventType, eventData)
  197. -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  198. -- Note the convenience accessor to the physics world component
  199. if drawDebug then
  200. scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true)
  201. end
  202. end
  203. -- Create XML patch instructions for screen joystick layout specific to this sample app
  204. function GetScreenJoystickPatchString()
  205. return
  206. "<patch>" ..
  207. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  208. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" ..
  209. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  210. " <element type=\"Text\">" ..
  211. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
  212. " <attribute name=\"Text\" value=\"LEFT\" />" ..
  213. " </element>" ..
  214. " </add>" ..
  215. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  216. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
  217. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  218. " <element type=\"Text\">" ..
  219. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  220. " <attribute name=\"Text\" value=\"SPACE\" />" ..
  221. " </element>" ..
  222. " </add>" ..
  223. "</patch>"
  224. end