46_RaycastVehicleDemo.as 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 int CTRL_BRAKE = 16;
  12. const float CAMERA_DISTANCE = 10.0f;
  13. const float YAW_SENSITIVITY = 0.1f;
  14. const float ENGINE_FORCE = 2500.0f;
  15. const float DOWN_FORCE = 100.0f;
  16. const float MAX_WHEEL_ANGLE = 22.5f;
  17. const float CHASSIS_WIDTH = 2.6f;
  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. // Set the mouse mode to use in the sample
  30. SampleInitMouseMode(MM_RELATIVE);
  31. // Subscribe to necessary events
  32. SubscribeToEvents();
  33. }
  34. void CreateScene()
  35. {
  36. scene_ = Scene();
  37. // Create scene subsystem components
  38. scene_.CreateComponent("Octree");
  39. scene_.CreateComponent("PhysicsWorld");
  40. // Create camera and define viewport. Camera does not necessarily have to belong to the scene
  41. cameraNode = Node();
  42. Camera@ camera = cameraNode.CreateComponent("Camera");
  43. camera.farClip = 500.0f;
  44. renderer.viewports[0] = Viewport(scene_, camera);
  45. // Create static scene content. First create a zone for ambient lighting and fog control
  46. Node@ zoneNode = scene_.CreateChild("Zone");
  47. Zone@ zone = zoneNode.CreateComponent("Zone");
  48. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  49. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  50. zone.fogStart = 300.0f;
  51. zone.fogEnd = 500.0f;
  52. zone.boundingBox = BoundingBox(-2000.0f, 2000.0f);
  53. // Create a directional light to the world. Enable cascaded shadows on it
  54. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  55. lightNode.direction = Vector3(0.3f, -0.5f, 0.425f);
  56. Light@ light = lightNode.CreateComponent("Light");
  57. light.lightType = LIGHT_DIRECTIONAL;
  58. light.castShadows = true;
  59. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  60. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  61. light.specularIntensity = 0.5f;
  62. // Create heightmap terrain with collision
  63. Node@ terrainNode = scene_.CreateChild("Terrain");
  64. terrainNode.position = Vector3(0.0f, 0.0f, 0.0f);
  65. Terrain@ terrain = terrainNode.CreateComponent("Terrain");
  66. terrain.patchSize = 64;
  67. terrain.spacing = Vector3(2.0f, 0.1f, 2.0f); // Spacing between vertices and vertical resolution of the height map
  68. terrain.smoothing = true;
  69. terrain.heightMap = cache.GetResource("Image", "Textures/HeightMap.png");
  70. terrain.material = cache.GetResource("Material", "Materials/Terrain.xml");
  71. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  72. // terrain patches and other objects behind it
  73. terrain.occluder = true;
  74. RigidBody@ body = terrainNode.CreateComponent("RigidBody");
  75. body.collisionLayer = 2; // Use layer bitmask 2 for static geometry
  76. CollisionShape@ shape = terrainNode.CreateComponent("CollisionShape");
  77. shape.SetTerrain();
  78. // Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
  79. const uint NUM_MUSHROOMS = 1000;
  80. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  81. {
  82. Node@ objectNode = scene_.CreateChild("Mushroom");
  83. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  84. position.y = terrain.GetHeight(position) - 0.1f;
  85. objectNode.position = position;
  86. // Create a rotation quaternion from up vector to terrain normal
  87. objectNode.rotation = Quaternion(Vector3(0.0f, 1.0f, 0.0), terrain.GetNormal(position));
  88. objectNode.SetScale(3.0f);
  89. StaticModel@ object = objectNode.CreateComponent("StaticModel");
  90. object.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  91. object.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  92. object.castShadows = true;
  93. RigidBody@ mushroomBody = objectNode.CreateComponent("RigidBody");
  94. mushroomBody.collisionLayer = 2;
  95. CollisionShape@ mushroomShape = objectNode.CreateComponent("CollisionShape");
  96. mushroomShape.SetTriangleMesh(object.model, 0);
  97. }
  98. }
  99. void CreateVehicle()
  100. {
  101. vehicleNode = scene_.CreateChild("Vehicle");
  102. vehicleNode.position = Vector3(0.0f, 5.0f, 0.0f);
  103. // First createing player-controlled vehicle
  104. // Create the vehicle logic script object
  105. Vehicle@ vehicle = cast<Vehicle>(vehicleNode.CreateScriptObject(scriptFile, "Vehicle"));
  106. // Initialize vehicle component
  107. vehicle.Init();
  108. vehicleNode.AddTag("vehicle");
  109. // Set RigidBody physics parameters
  110. // (The RigidBody was created by vehicle.Init()
  111. RigidBody@ hullBody = vehicleNode.GetComponent("RigidBody");
  112. hullBody.mass = 800.0f;
  113. hullBody.linearDamping = 0.2f; // Some air resistance
  114. hullBody.angularDamping = 0.5f;
  115. hullBody.collisionLayer = 1;
  116. }
  117. void CreateInstructions()
  118. {
  119. // Construct new Text object, set string to display and font to use
  120. Text@ instructionText = ui.root.CreateChild("Text");
  121. instructionText.text =
  122. "Use WASD keys to drive, F to brake, mouse/touch to rotate camera\n"
  123. "F5 to save scene, F7 to load";
  124. instructionText.
  125. SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  126. // The text has multiple rows. Center them in relation to each other
  127. instructionText.textAlignment = HA_CENTER;
  128. // Position the text relative to the screen center
  129. instructionText.horizontalAlignment = HA_CENTER;
  130. instructionText.verticalAlignment = VA_CENTER;
  131. instructionText.SetPosition(0, ui.root.height / 4);
  132. }
  133. void SubscribeToEvents()
  134. {
  135. // Subscribe to Update event for setting the vehicle controls before physics simulation
  136. SubscribeToEvent("Update", "HandleUpdate");
  137. // Subscribe to PostUpdate event for updating the camera position after physics simulation
  138. SubscribeToEvent("PostUpdate", "HandlePostUpdate");
  139. // Unsubscribe the SceneUpdate event from base class as the camera node is being controlled in HandlePostUpdate() in this sample
  140. UnsubscribeFromEvent("SceneUpdate");
  141. }
  142. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  143. {
  144. if (vehicleNode is null)
  145. return;
  146. Vehicle@ vehicle = cast < Vehicle > (vehicleNode.scriptObject);
  147. if (vehicle is null)
  148. return;
  149. // Get movement controls and assign them to the vehicle component. If UI has a focused element, clear controls
  150. if (ui.focusElement is null)
  151. {
  152. vehicle.controls.Set(CTRL_FORWARD, input.keyDown[KEY_W]);
  153. vehicle.controls.Set(CTRL_BACK, input.keyDown[KEY_S]);
  154. vehicle.controls.Set(CTRL_LEFT, input.keyDown[KEY_A]);
  155. vehicle.controls.Set(CTRL_RIGHT, input.keyDown[KEY_D]);
  156. vehicle.controls.Set(CTRL_BRAKE, input.keyDown[KEY_F]);
  157. // Add yaw & pitch from the mouse motion. Used only for the camera, does not affect motion
  158. if (touchEnabled)
  159. {
  160. for (uint i = 0; i < input.numTouches; ++i)
  161. {
  162. TouchState@ state = input.touches[i];
  163. if (state.touchedElement is null) // Touch on empty space
  164. {
  165. Camera@ camera = cameraNode.GetComponent("Camera");
  166. if (camera is null)
  167. return;
  168. vehicle.controls.yaw += TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.x;
  169. vehicle.controls.pitch += TOUCH_SENSITIVITY * camera.fov / graphics.height * state.delta.y;
  170. }
  171. }
  172. }
  173. else
  174. {
  175. vehicle.controls.yaw += input.mouseMoveX * YAW_SENSITIVITY;
  176. vehicle.controls.pitch += input.mouseMoveY * YAW_SENSITIVITY;
  177. }
  178. // Limit pitch
  179. vehicle.controls.pitch = Clamp(vehicle.controls.pitch, 0.0f, 80.0f);
  180. // Check for loading / saving the scene
  181. if (input.keyPress[KEY_F5])
  182. {
  183. File saveFile(fileSystem.programDir + "Data/Scenes/RaycastScriptVehicleDemo.xml", FILE_WRITE);
  184. scene_.SaveXML(saveFile);
  185. }
  186. if (input.keyPress[KEY_F7])
  187. {
  188. File loadFile(fileSystem.programDir + "Data/Scenes/RaycastScriptVehicleDemo.xml", FILE_READ);
  189. scene_.LoadXML(loadFile);
  190. // After loading we have to reacquire the vehicle scene node, as it has been recreated
  191. // Simply find by name as there's only one of them
  192. Array<Node@>@ vehicles = scene_.GetChildrenWithTag("vehicle");
  193. for (int i = 0; i < vehicles.length; i++)
  194. {
  195. Vehicle@ vehicleData = cast<Vehicle>(vehicles[i].scriptObject);
  196. vehicleData.CreateEmitters();
  197. }
  198. vehicleNode = scene_.GetChild("Vehicle", true);
  199. }
  200. }
  201. else
  202. vehicle.controls.Set(CTRL_FORWARD | CTRL_BACK | CTRL_LEFT | CTRL_RIGHT | CTRL_BRAKE, false);
  203. }
  204. void HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  205. {
  206. if (vehicleNode is null)
  207. return;
  208. Vehicle@ vehicle = cast < Vehicle > (vehicleNode.scriptObject);
  209. if (vehicle is null)
  210. return;
  211. // Physics update has completed. Position camera behind vehicle
  212. Quaternion dir(vehicleNode.rotation.yaw, Vector3(0.0f, 1.0f, 0.0f));
  213. dir = dir * Quaternion(vehicle.controls.yaw, Vector3(0.0f, 1.0f, 0.0f));
  214. dir = dir * Quaternion(vehicle.controls.pitch, Vector3(1.0f, 0.0f, 0.0f));
  215. Vector3 cameraTargetPos = vehicleNode.position - dir * Vector3(0.0f, 0.0f, CAMERA_DISTANCE);
  216. Vector3 cameraStartPos = vehicleNode.position;
  217. // Raycast camera against static objects (physics collision mask 2)
  218. // and move it closer to the vehicle if something in between
  219. Ray cameraRay(cameraStartPos, (cameraTargetPos - cameraStartPos).Normalized());
  220. float cameraRayLength = (cameraTargetPos - cameraStartPos).length;
  221. PhysicsRaycastResult result = scene_.physicsWorld.RaycastSingle(cameraRay, cameraRayLength, 2);
  222. if (result.body !is null)
  223. cameraTargetPos = cameraStartPos + cameraRay.direction * (result.distance - 0.5f);
  224. cameraNode.position = cameraTargetPos;
  225. cameraNode.rotation = dir;
  226. }
  227. // Vehicle script object class
  228. //
  229. // When saving, the node and component handles are automatically converted into nodeID or componentID attributes
  230. // and are acquired from the scene when loading. The steering member variable will likewise be saved automatically.
  231. // The Controls object can not be automatically saved, so handle it manually in the Load() and Save() methods
  232. class Vehicle:ScriptObject
  233. {
  234. RigidBody@ hullBody;
  235. // Current left/right steering amount (-1 to 1.)
  236. float steering = 0.0f;
  237. // Vehicle controls.
  238. Controls controls;
  239. float suspensionRestLength = 0.6f;
  240. float suspensionStiffness = 14.0f;
  241. float suspensionDamping = 2.0f;
  242. float suspensionCompression = 4.0f;
  243. float wheelFriction = 1000.0f;
  244. float rollInfluence = 0.12f;
  245. float maxEngineForce = ENGINE_FORCE;
  246. float wheelWidth = 0.4f;
  247. float wheelRadius = 0.5f;
  248. float brakingForce = 50.0f;
  249. Array<Vector3> connectionPoints;
  250. Array<Node@> particleEmitterNodeList;
  251. protected Vector3 prevVelocity;
  252. void Load(Deserializer& deserializer)
  253. {
  254. controls.yaw = deserializer.ReadFloat();
  255. controls.pitch = deserializer.ReadFloat();
  256. }
  257. void Save(Serializer& serializer)
  258. {
  259. serializer.WriteFloat(controls.yaw);
  260. serializer.WriteFloat(controls.pitch);
  261. }
  262. void Init()
  263. {
  264. // This function is called only from the main program when initially creating the vehicle, not on scene load
  265. StaticModel@ hullObject = node.CreateComponent("StaticModel");
  266. hullBody = node.CreateComponent("RigidBody");
  267. CollisionShape@ hullShape = node.CreateComponent("CollisionShape");
  268. node.scale = Vector3(2.3f, 1.0f, 4.0f);
  269. hullObject.model = cache.GetResource("Model", "Models/Box.mdl");
  270. hullObject.material = cache.GetResource("Material", "Materials/Stone.xml");
  271. hullObject.castShadows = true;
  272. hullShape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  273. hullBody.mass = 800.0f;
  274. hullBody.linearDamping = 0.2f; // Some air resistance
  275. hullBody.angularDamping = 0.5f;
  276. hullBody.collisionLayer = 1;
  277. RaycastVehicle@ raycastVehicle = node.CreateComponent("RaycastVehicle");
  278. raycastVehicle.Init();
  279. connectionPoints.Reserve(4);
  280. float connectionHeight = -0.4f; //1.2f;
  281. bool isFrontWheel = true;
  282. Vector3 wheelDirection(0, -1, 0);
  283. Vector3 wheelAxle(-1, 0, 0);
  284. float wheelX = CHASSIS_WIDTH / 2.0 - wheelWidth;
  285. // Front left
  286. connectionPoints.Push(Vector3(-wheelX, connectionHeight, 2.5f - wheelRadius * 2.0f));
  287. // Front right
  288. connectionPoints.Push(Vector3(wheelX, connectionHeight, 2.5f - wheelRadius * 2.0f));
  289. // Back left
  290. connectionPoints.Push(Vector3(-wheelX, connectionHeight, -2.5f + wheelRadius * 2.0f));
  291. // Back right
  292. connectionPoints.Push(Vector3(wheelX, connectionHeight, -2.5f + wheelRadius * 2.0f));
  293. const Color LtBrown(0.972f, 0.780f, 0.412f);
  294. for (int id = 0; id < connectionPoints.length; id++)
  295. {
  296. Node@ wheelNode = scene_.CreateChild();
  297. Vector3 connectionPoint = connectionPoints[id];
  298. // Front wheels are at front (z > 0)
  299. // back wheels are at z < 0
  300. // Setting rotation according to wheel position
  301. bool isFrontWheel = connectionPoints[id].z > 0.0f;
  302. wheelNode.rotation = (connectionPoint.x >= 0.0 ? Quaternion(0.0f, 0.0f, -90.0f) : Quaternion(0.0f, 0.0f, 90.0f));
  303. wheelNode.worldPosition = (node.worldPosition + node.worldRotation * connectionPoints[id]);
  304. wheelNode.scale = Vector3(1.0f, 0.65f, 1.0f);
  305. raycastVehicle.AddWheel(wheelNode, wheelDirection, wheelAxle, suspensionRestLength, wheelRadius, isFrontWheel);
  306. raycastVehicle.SetWheelSuspensionStiffness(id, suspensionStiffness);
  307. raycastVehicle.SetWheelDampingRelaxation(id, suspensionDamping);
  308. raycastVehicle.SetWheelDampingCompression(id, suspensionCompression);
  309. raycastVehicle.SetWheelFrictionSlip(id, wheelFriction);
  310. raycastVehicle.SetWheelRollInfluence(id, rollInfluence);
  311. StaticModel@ pWheel = wheelNode.CreateComponent("StaticModel");
  312. pWheel.model = cache.GetResource("Model", "Models/Cylinder.mdl");
  313. pWheel.material = cache.GetResource("Material", "Materials/Stone.xml");
  314. pWheel.castShadows = true;
  315. }
  316. CreateEmitters();
  317. raycastVehicle.ResetWheels();
  318. }
  319. void CreateEmitter(Vector3 place)
  320. {
  321. Node@ emitter = scene_.CreateChild();
  322. emitter.worldPosition = node.worldPosition + node.worldRotation * place + Vector3(0, -wheelRadius, 0);
  323. ParticleEmitter@ particleEmitter = emitter.CreateComponent("ParticleEmitter");
  324. particleEmitter.effect = cache.GetResource("ParticleEffect", "Particle/Dust.xml");
  325. particleEmitter.emitting = false;
  326. particleEmitterNodeList.Push(emitter);
  327. emitter.temporary = true;
  328. }
  329. void CreateEmitters()
  330. {
  331. particleEmitterNodeList.Clear();
  332. RaycastVehicle@ raycastVehicle = node.GetComponent("RaycastVehicle");
  333. for (int id = 0; id < raycastVehicle.numWheels; id++)
  334. {
  335. Vector3 connectionPoint = raycastVehicle.GetWheelConnectionPoint(id);
  336. CreateEmitter(connectionPoint);
  337. }
  338. }
  339. void FixedUpdate(float timeStep)
  340. {
  341. float newSteering = 0.0f;
  342. float accelerator = 0.0f;
  343. bool brake = false;
  344. RaycastVehicle@ raycastVehicle = node.GetComponent("RaycastVehicle");
  345. if (controls.IsDown(CTRL_LEFT))
  346. newSteering = -1.0f;
  347. if (controls.IsDown(CTRL_RIGHT))
  348. newSteering = 1.0f;
  349. if (controls.IsDown(CTRL_FORWARD))
  350. accelerator = 1.0f;
  351. if (controls.IsDown(CTRL_BACK))
  352. accelerator = -0.5f;
  353. if (controls.IsDown(CTRL_BRAKE))
  354. brake = true;
  355. // When steering, wake up the wheel rigidbodies so that their orientation is updated
  356. if (newSteering != 0.0f)
  357. {
  358. steering = steering * 0.95f + newSteering * 0.05f;
  359. }
  360. else
  361. steering = steering * 0.8f + newSteering * 0.2f;
  362. Quaternion steeringRot(0.0f, steering * MAX_WHEEL_ANGLE, 0.0f);
  363. raycastVehicle.SetSteeringValue(0, steering);
  364. raycastVehicle.SetSteeringValue(1, steering);
  365. raycastVehicle.SetEngineForce(2, maxEngineForce * accelerator);
  366. raycastVehicle.SetEngineForce(3, maxEngineForce * accelerator);
  367. for (int i = 0; i < raycastVehicle.numWheels; i++)
  368. {
  369. if (brake)
  370. {
  371. raycastVehicle.SetBrake(i, brakingForce);
  372. }
  373. else
  374. {
  375. raycastVehicle.SetBrake(i, 0.0f);
  376. }
  377. }
  378. // Apply downforce proportional to velocity
  379. Vector3 localVelocity = hullBody.rotation.Inverse() * hullBody.linearVelocity;
  380. hullBody.ApplyForce(hullBody.rotation * Vector3(0.0f, -1.0f, 0.0f) * Abs(localVelocity.z) * DOWN_FORCE);
  381. }
  382. void PostUpdate(float timeStep)
  383. {
  384. if (particleEmitterNodeList.length == 0)
  385. return;
  386. RaycastVehicle@ raycastVehicle = node.GetComponent("RaycastVehicle");
  387. RigidBody@ vehicleBody = node.GetComponent("RigidBody");
  388. Vector3 velocity = hullBody.linearVelocity;
  389. Vector3 accel = (velocity - prevVelocity) / timeStep;
  390. float planeAccel = Vector3(accel.x, 0.0f, accel.z).length;
  391. for (int i = 0; i < raycastVehicle.numWheels; i++)
  392. {
  393. Node@ emitter = particleEmitterNodeList[i];
  394. ParticleEmitter@ particleEmitter = emitter.GetComponent("ParticleEmitter");
  395. if (raycastVehicle.WheelIsGrounded(i) && (raycastVehicle.GetWheelSkidInfoCumulative(i) < 0.9f || raycastVehicle.GetBrake(i) > 2.0f ||
  396. planeAccel > 15.0f))
  397. {
  398. emitter.worldPosition = raycastVehicle.GetContactPosition(i);
  399. if (!particleEmitter.emitting)
  400. particleEmitter.emitting = true;
  401. }
  402. else if (particleEmitter.emitting)
  403. particleEmitter.emitting = false;
  404. }
  405. prevVelocity = velocity;
  406. }
  407. }
  408. // Create XML patch instructions for screen joystick layout specific to this sample app
  409. String patchInstructions = "";