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