19_VehicleDemo.lua 16 KB

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