11_Physics.as 12 KB

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