19_VehicleDemo.as 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // Vehicle example.
  2. // This sample demonstrates:
  3. // - Creating a heightmap terrain with collision
  4. // - Constructing a physical vehicle with rigid bodies for the hull and the wheels, joined with constraints
  5. // - Saving and loading the variables of a script object, including node & component references
  6. #include "Scripts/Utilities/Sample.as"
  7. const int CTRL_FORWARD = 1;
  8. const int CTRL_BACK = 2;
  9. const int CTRL_LEFT = 4;
  10. const int CTRL_RIGHT = 8;
  11. const float CAMERA_DISTANCE = 10.0f;
  12. const float YAW_SENSITIVITY = 0.1f;
  13. const float ENGINE_POWER = 10.0f;
  14. const float DOWN_FORCE = 10.0f;
  15. const float MAX_WHEEL_ANGLE = 22.5f;
  16. Node@ vehicleNode;
  17. void Start()
  18. {
  19. // Execute the common startup for samples
  20. SampleStart();
  21. // Create static scene content
  22. CreateScene();
  23. // Create the controllable vehicle
  24. CreateVehicle();
  25. // Create the UI content
  26. CreateInstructions();
  27. // Subscribe to necessary events
  28. SubscribeToEvents();
  29. }
  30. void CreateScene()
  31. {
  32. scene_ = Scene();
  33. // Create scene subsystem components
  34. scene_.CreateComponent("Octree");
  35. scene_.CreateComponent("PhysicsWorld");
  36. // Create camera and define viewport. Camera does not necessarily have to belong to the scene
  37. cameraNode = Node();
  38. Camera@ camera = cameraNode.CreateComponent("Camera");
  39. camera.farClip = 500.0f;
  40. renderer.viewports[0] = Viewport(scene_, camera);
  41. // Create static scene content. First create a zone for ambient lighting and fog control
  42. Node@ zoneNode = scene_.CreateChild("Zone");
  43. Zone@ zone = zoneNode.CreateComponent("Zone");
  44. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  45. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  46. zone.fogStart = 300.0f;
  47. zone.fogEnd = 500.0f;
  48. zone.boundingBox = BoundingBox(-2000.0f, 2000.0f);
  49. // Create a directional light to the world. Enable cascaded shadows on it
  50. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  51. lightNode.direction = Vector3(0.3f, -0.5f, 0.425f);
  52. Light@ light = lightNode.CreateComponent("Light");
  53. light.lightType = LIGHT_DIRECTIONAL;
  54. light.castShadows = true;
  55. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  56. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  57. light.specularIntensity = 0.5f;
  58. // Create heightmap terrain with collision
  59. Node@ terrainNode = scene_.CreateChild("Terrain");
  60. terrainNode.position = Vector3(0.0f, 0.0f, 0.0f);
  61. Terrain@ terrain = terrainNode.CreateComponent("Terrain");
  62. terrain.patchSize = 64;
  63. terrain.spacing = Vector3(2.0f, 0.1f, 2.0f); // Spacing between vertices and vertical resolution of the height map
  64. terrain.smoothing = true;
  65. terrain.heightMap = cache.GetResource("Image", "Textures/HeightMap.png");
  66. terrain.material = cache.GetResource("Material", "Materials/Terrain.xml");
  67. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  68. // terrain patches and other objects behind it
  69. terrain.occluder = true;
  70. RigidBody@ body = terrainNode.CreateComponent("RigidBody");
  71. body.collisionLayer = 2; // Use layer bitmask 2 for static geometry
  72. CollisionShape@ shape = terrainNode.CreateComponent("CollisionShape");
  73. shape.SetTerrain();
  74. // Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
  75. const uint NUM_MUSHROOMS = 1000;
  76. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  77. {
  78. Node@ objectNode = scene_.CreateChild("Mushroom");
  79. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  80. position.y = terrain.GetHeight(position) - 0.1f;
  81. objectNode.position = position;
  82. // Create a rotation quaternion from up vector to terrain normal
  83. objectNode.rotation = Quaternion(Vector3(0.0f, 1.0f, 0.0), terrain.GetNormal(position));
  84. objectNode.SetScale(3.0f);
  85. StaticModel@ object = objectNode.CreateComponent("StaticModel");
  86. object.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  87. object.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  88. object.castShadows = true;
  89. RigidBody@ body = objectNode.CreateComponent("RigidBody");
  90. body.collisionLayer = 2;
  91. CollisionShape@ shape = objectNode.CreateComponent("CollisionShape");
  92. shape.SetTriangleMesh(object.model, 0);
  93. }
  94. }
  95. void CreateVehicle()
  96. {
  97. vehicleNode = scene_.CreateChild("Vehicle");
  98. vehicleNode.position = Vector3(0.0f, 5.0f, 0.0f);
  99. // Create the vehicle logic script object
  100. Vehicle@ vehicle = cast<Vehicle>(vehicleNode.CreateScriptObject(scriptFile, "Vehicle"));
  101. // Create the rendering and physics components
  102. vehicle.Init();
  103. }
  104. void CreateInstructions()
  105. {
  106. // Construct new Text object, set string to display and font to use
  107. Text@ instructionText = ui.root.CreateChild("Text");
  108. instructionText.text = "Use WASD keys to drive, mouse/touch to rotate camera\n"
  109. "F5 to save scene, F7 to load";
  110. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  111. // The text has multiple rows. Center them in relation to each other
  112. instructionText.textAlignment = HA_CENTER;
  113. // Position the text relative to the screen center
  114. instructionText.horizontalAlignment = HA_CENTER;
  115. instructionText.verticalAlignment = VA_CENTER;
  116. instructionText.SetPosition(0, ui.root.height / 4);
  117. }
  118. void SubscribeToEvents()
  119. {
  120. // Subscribe to Update event for setting the vehicle controls before physics simulation
  121. SubscribeToEvent("Update", "HandleUpdate");
  122. // Subscribe to PostUpdate event for updating the camera position after physics simulation
  123. SubscribeToEvent("PostUpdate", "HandlePostUpdate");
  124. // Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample
  125. UnsubscribeFromEvent("SceneUpdate");
  126. }
  127. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  128. {
  129. if (vehicleNode is null)
  130. return;
  131. Vehicle@ vehicle = cast<Vehicle>(vehicleNode.scriptObject);
  132. if (vehicle is null)
  133. return;
  134. // Get movement controls and assign them to the vehicle component. If UI has a focused element, clear controls
  135. if (ui.focusElement is null)
  136. {
  137. vehicle.controls.Set(CTRL_FORWARD, input.keyDown['W']);
  138. vehicle.controls.Set(CTRL_BACK, input.keyDown['S']);
  139. vehicle.controls.Set(CTRL_LEFT, input.keyDown['A']);
  140. vehicle.controls.Set(CTRL_RIGHT, input.keyDown['D']);
  141. // Add yaw & pitch from the mouse motion. Used only for the camera, does not affect motion
  142. if (touchEnabled)
  143. {
  144. for (uint i = 0; i < input.numTouches; ++i)
  145. {
  146. TouchState@ state = input.touches[i];
  147. if (state.touchedElement is null) // Touch on empty space
  148. {
  149. Camera@ camera = cameraNode.GetComponent("Camera");
  150. if (camera is null)
  151. return;
  152. vehicle.controls.yaw += TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.x;
  153. vehicle.controls.pitch += TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.y;
  154. }
  155. }
  156. }
  157. else
  158. {
  159. vehicle.controls.yaw += input.mouseMoveX * YAW_SENSITIVITY;
  160. vehicle.controls.pitch += input.mouseMoveY * YAW_SENSITIVITY;
  161. }
  162. // Limit pitch
  163. vehicle.controls.pitch = Clamp(vehicle.controls.pitch, 0.0f, 80.0f);
  164. // Check for loading / saving the scene
  165. if (input.keyPress[KEY_F5])
  166. {
  167. File saveFile(fileSystem.programDir + "Data/Scenes/VehicleDemo.xml", FILE_WRITE);
  168. scene_.SaveXML(saveFile);
  169. }
  170. if (input.keyPress[KEY_F7])
  171. {
  172. File loadFile(fileSystem.programDir + "Data/Scenes/VehicleDemo.xml", FILE_READ);
  173. scene_.LoadXML(loadFile);
  174. // After loading we have to reacquire the vehicle scene node, as it has been recreated
  175. // Simply find by name as there's only one of them
  176. vehicleNode = scene_.GetChild("Vehicle", true);
  177. }
  178. }
  179. else
  180. vehicle.controls.Set(CTRL_FORWARD | CTRL_BACK | CTRL_LEFT | CTRL_RIGHT, false);
  181. }
  182. void HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  183. {
  184. if (vehicleNode is null)
  185. return;
  186. Vehicle@ vehicle = cast<Vehicle>(vehicleNode.scriptObject);
  187. if (vehicle is null)
  188. return;
  189. // Physics update has completed. Position camera behind vehicle
  190. Quaternion dir(vehicleNode.rotation.yaw, Vector3(0.0f, 1.0f, 0.0f));
  191. dir = dir * Quaternion(vehicle.controls.yaw, Vector3(0.0f, 1.0f, 0.0f));
  192. dir = dir * Quaternion(vehicle.controls.pitch, Vector3(1.0f, 0.0f, 0.0f));
  193. Vector3 cameraTargetPos = vehicleNode.position - dir * Vector3(0.0f, 0.0f, CAMERA_DISTANCE);
  194. Vector3 cameraStartPos = vehicleNode.position;
  195. // Raycast camera against static objects (physics collision mask 2)
  196. // and move it closer to the vehicle if something in between
  197. Ray cameraRay(cameraStartPos, (cameraTargetPos - cameraStartPos).Normalized());
  198. float cameraRayLength = (cameraTargetPos - cameraStartPos).length;
  199. PhysicsRaycastResult result = scene_.physicsWorld.RaycastSingle(cameraRay, cameraRayLength, 2);
  200. if (result.body !is null)
  201. cameraTargetPos = cameraStartPos + cameraRay.direction * (result.distance - 0.5f);
  202. cameraNode.position = cameraTargetPos;
  203. cameraNode.rotation = dir;
  204. }
  205. // Vehicle script object class
  206. //
  207. // When saving, the node and component handles are automatically converted into nodeID or componentID attributes
  208. // and are acquired from the scene when loading. The steering member variable will likewise be saved automatically.
  209. // The Controls object can not be automatically saved, so handle it manually in the Load() and Save() methods
  210. class Vehicle : ScriptObject
  211. {
  212. Node@ frontLeft;
  213. Node@ frontRight;
  214. Node@ rearLeft;
  215. Node@ rearRight;
  216. Constraint@ frontLeftAxis;
  217. Constraint@ frontRightAxis;
  218. RigidBody@ hullBody;
  219. RigidBody@ frontLeftBody;
  220. RigidBody@ frontRightBody;
  221. RigidBody@ rearLeftBody;
  222. RigidBody@ rearRightBody;
  223. // Current left/right steering amount (-1 to 1.)
  224. float steering = 0.0f;
  225. // Vehicle controls.
  226. Controls controls;
  227. void Load(Deserializer& deserializer)
  228. {
  229. controls.yaw = deserializer.ReadFloat();
  230. controls.pitch = deserializer.ReadFloat();
  231. }
  232. void Save(Serializer& serializer)
  233. {
  234. serializer.WriteFloat(controls.yaw);
  235. serializer.WriteFloat(controls.pitch);
  236. }
  237. void Init()
  238. {
  239. // This function is called only from the main program when initially creating the vehicle, not on scene load
  240. StaticModel@ hullObject = node.CreateComponent("StaticModel");
  241. hullBody = node.CreateComponent("RigidBody");
  242. CollisionShape@ hullShape = node.CreateComponent("CollisionShape");
  243. node.scale = Vector3(1.5f, 1.0f, 3.0f);
  244. hullObject.model = cache.GetResource("Model", "Models/Box.mdl");
  245. hullObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  246. hullObject.castShadows = true;
  247. hullShape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  248. hullBody.mass = 4.0f;
  249. hullBody.linearDamping = 0.2f; // Some air resistance
  250. hullBody.angularDamping = 0.5f;
  251. hullBody.collisionLayer = 1;
  252. frontLeft = InitWheel("FrontLeft", Vector3(-0.6f, -0.4f, 0.3f));
  253. frontRight = InitWheel("FrontRight", Vector3(0.6f, -0.4f, 0.3f));
  254. rearLeft = InitWheel("RearLeft", Vector3(-0.6f, -0.4f, -0.3f));
  255. rearRight = InitWheel("RearRight", Vector3(0.6f, -0.4f, -0.3f));
  256. frontLeftAxis = frontLeft.GetComponent("Constraint");
  257. frontRightAxis = frontRight.GetComponent("Constraint");
  258. frontLeftBody = frontLeft.GetComponent("RigidBody");
  259. frontRightBody = frontRight.GetComponent("RigidBody");
  260. rearLeftBody = rearLeft.GetComponent("RigidBody");
  261. rearRightBody = rearRight.GetComponent("RigidBody");
  262. }
  263. Node@ InitWheel(const String&in name, const Vector3&in offset)
  264. {
  265. // Note: do not parent the wheel to the hull scene node. Instead create it on the root level and let the physics
  266. // constraint keep it together
  267. Node@ wheelNode = scene.CreateChild(name);
  268. wheelNode.position = node.LocalToWorld(offset);
  269. wheelNode.rotation = node.worldRotation * (offset.x >= 0.0f ? Quaternion(0.0f, 0.0f, -90.0f) :
  270. Quaternion(0.0f, 0.0f, 90.0f));
  271. wheelNode.scale = Vector3(0.8f, 0.5f, 0.8f);
  272. StaticModel@ wheelObject = wheelNode.CreateComponent("StaticModel");
  273. RigidBody@ wheelBody = wheelNode.CreateComponent("RigidBody");
  274. CollisionShape@ wheelShape = wheelNode.CreateComponent("CollisionShape");
  275. Constraint@ wheelConstraint = wheelNode.CreateComponent("Constraint");
  276. wheelObject.model = cache.GetResource("Model", "Models/Cylinder.mdl");
  277. wheelObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  278. wheelObject.castShadows = true;
  279. wheelShape.SetSphere(1.0f);
  280. wheelBody.friction = 1;
  281. wheelBody.mass = 1;
  282. wheelBody.linearDamping = 0.2f; // Some air resistance
  283. wheelBody.angularDamping = 0.75f; // Could also use rolling friction
  284. wheelBody.collisionLayer = 1;
  285. wheelConstraint.constraintType = CONSTRAINT_HINGE;
  286. wheelConstraint.otherBody = node.GetComponent("RigidBody");
  287. wheelConstraint.worldPosition = wheelNode.worldPosition; // Set constraint's both ends at wheel's location
  288. wheelConstraint.axis = Vector3(0.0f, 1.0f, 0.0f); // Wheel rotates around its local Y-axis
  289. wheelConstraint.otherAxis = offset.x >= 0.0f ? Vector3(1.0f, 0.0f, 0.0f) : Vector3(-1.0f, 0.0f, 0.0f); // Wheel's hull axis points either left or right
  290. wheelConstraint.lowLimit = Vector2(-180.0f, 0.0f); // Let the wheel rotate freely around the axis
  291. wheelConstraint.highLimit = Vector2(180.0f, 0.0f);
  292. wheelConstraint.disableCollision = true; // Let the wheel intersect the vehicle hull
  293. return wheelNode;
  294. }
  295. void FixedUpdate(float timeStep)
  296. {
  297. float newSteering = 0.0f;
  298. float accelerator = 0.0f;
  299. if (controls.IsDown(CTRL_LEFT))
  300. newSteering = -1.0f;
  301. if (controls.IsDown(CTRL_RIGHT))
  302. newSteering = 1.0f;
  303. if (controls.IsDown(CTRL_FORWARD))
  304. accelerator = 1.0f;
  305. if (controls.IsDown(CTRL_BACK))
  306. accelerator = -0.5f;
  307. // When steering, wake up the wheel rigidbodies so that their orientation is updated
  308. if (newSteering != 0.0f)
  309. {
  310. frontLeftBody.Activate();
  311. frontRightBody.Activate();
  312. steering = steering * 0.95f + newSteering * 0.05f;
  313. }
  314. else
  315. steering = steering * 0.8f + newSteering * 0.2f;
  316. Quaternion steeringRot(0.0f, steering * MAX_WHEEL_ANGLE, 0.0f);
  317. frontLeftAxis.otherAxis = steeringRot * Vector3(-1.0f, 0.0f, 0.0f);
  318. frontRightAxis.otherAxis = steeringRot * Vector3(1.0f, 0.0f, 0.0f);
  319. if (accelerator != 0.0f)
  320. {
  321. // Torques are applied in world space, so need to take the vehicle & wheel rotation into account
  322. Vector3 torqueVec = Vector3(ENGINE_POWER * accelerator, 0.0f, 0.0f);
  323. frontLeftBody.ApplyTorque(node.rotation * steeringRot * torqueVec);
  324. frontRightBody.ApplyTorque(node.rotation * steeringRot * torqueVec);
  325. rearLeftBody.ApplyTorque(node.rotation * torqueVec);
  326. rearRightBody.ApplyTorque(node.rotation * torqueVec);
  327. }
  328. // Apply downforce proportional to velocity
  329. Vector3 localVelocity = hullBody.rotation.Inverse() * hullBody.linearVelocity;
  330. hullBody.ApplyForce(hullBody.rotation * Vector3(0.0f, -1.0f, 0.0f) * Abs(localVelocity.z) * DOWN_FORCE);
  331. }
  332. }
  333. // Create XML patch instructions for screen joystick layout specific to this sample app
  334. String patchInstructions = "";