19_VehicleDemo.lua 16 KB

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