19_VehicleDemo.as 15 KB

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