32_Urho2DConstraints.lua 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. -- Urho2D physics Constraints sample.
  2. -- This sample is designed to help understanding and chosing the right constraint.
  3. -- This sample demonstrates:
  4. -- - Creating physics constraints
  5. -- - Creating Edge and Polygon Shapes from vertices
  6. -- - Displaying physics debug geometry and constraints' joints
  7. -- - Using SetOrderInLayer to alter the way sprites are drawn in relation to each other
  8. -- - Using Text3D to display some text affected by zoom
  9. -- - Setting the background color for the scene
  10. require "LuaScripts/Utilities/Sample"
  11. local camera = nil
  12. local physicsWorld = nil
  13. local pickedNode = nil
  14. local dummyBody = nil
  15. function Start()
  16. SampleStart()
  17. CreateScene()
  18. input.mouseVisible = true -- Show mouse cursor
  19. CreateInstructions()
  20. SubscribeToEvents()
  21. end
  22. function CreateScene()
  23. scene_ = Scene()
  24. scene_:CreateComponent("Octree")
  25. scene_:CreateComponent("DebugRenderer")
  26. physicsWorld = scene_:CreateComponent("PhysicsWorld2D")
  27. physicsWorld.drawJoint = true -- Display the joints (Note that DrawDebugGeometry() must be set to true to acually draw the joints)
  28. drawDebug = true -- Set DrawDebugGeometry() to true
  29. -- Create camera
  30. cameraNode = scene_:CreateChild("Camera")
  31. cameraNode.position = Vector3(0, 0, 0) -- Note that Z setting is discarded; use camera.zoom instead (see MoveCamera() below for example)
  32. camera = cameraNode:CreateComponent("Camera")
  33. camera.orthographic = true
  34. camera.orthoSize = graphics.height * PIXEL_SIZE
  35. camera.zoom = 1.2
  36. renderer:SetViewport(0, Viewport:new(scene_, camera))
  37. renderer.defaultZone.fogColor = Color(0.1, 0.1, 0.1) -- Set background color for the scene
  38. -- Create a 4x3 grid
  39. for i=0, 4 do
  40. local edgeNode = scene_:CreateChild("VerticalEdge")
  41. local edgeBody = edgeNode:CreateComponent("RigidBody2D")
  42. if dummyBody == nil then dummyBody = edgeBody end -- Mark first edge as dummy body (used by mouse pick)
  43. local edgeShape = edgeNode:CreateComponent("CollisionEdge2D")
  44. edgeShape:SetVertices(Vector2(i*2.5 -5, -3), Vector2(i*2.5 -5, 3))
  45. edgeShape.friction = 0.5 -- Set friction
  46. end
  47. for j=0, 3 do
  48. local edgeNode = scene_:CreateChild("HorizontalEdge")
  49. local edgeBody = edgeNode:CreateComponent("RigidBody2D")
  50. local edgeShape = edgeNode:CreateComponent("CollisionEdge2D")
  51. edgeShape:SetVertices(Vector2(-5, j*2 -3), Vector2(5, j*2 -3))
  52. edgeShape.friction = 0.5 -- Set friction
  53. end
  54. -- Create a box (will be cloned later)
  55. local box = scene_:CreateChild("Box")
  56. box.position = Vector3(0.8, -2, 0)
  57. local staticSprite = box:CreateComponent("StaticSprite2D")
  58. staticSprite.sprite = cache:GetResource("Sprite2D", "Urho2D/Box.png")
  59. local body = box:CreateComponent("RigidBody2D")
  60. body.bodyType = BT_DYNAMIC
  61. body.linearDamping = 0
  62. body.angularDamping = 0
  63. local shape = box:CreateComponent("CollisionBox2D") -- Create box shape
  64. shape.size = Vector2(0.32, 0.32) -- Set size
  65. shape.density = 1 -- Set shape density (kilograms per meter squared)
  66. shape.friction = 0.5 -- Set friction
  67. shape.restitution = 0.1 -- Set restitution (slight bounce)
  68. -- Create a ball (will be cloned later)
  69. local ball = scene_:CreateChild("Ball")
  70. ball.position = Vector3(1.8, -2, 0)
  71. local staticSprite = ball:CreateComponent("StaticSprite2D")
  72. staticSprite.sprite = cache:GetResource("Sprite2D", "Urho2D/Ball.png")
  73. local body = ball:CreateComponent("RigidBody2D")
  74. body.bodyType = BT_DYNAMIC
  75. body.linearDamping = 0
  76. body.angularDamping = 0
  77. local shape = ball:CreateComponent("CollisionCircle2D") -- Create circle shape
  78. shape.radius = 0.16 -- Set radius
  79. shape.density = 1 -- Set shape density (kilograms per meter squared)
  80. shape.friction = 0.5 -- Set friction
  81. shape.restitution = 0.6 -- Set restitution: make it bounce
  82. -- Create a polygon
  83. local node = scene_:CreateChild("Polygon")
  84. node.position = Vector3(1.6, -2, 0)
  85. node:SetScale(0.7)
  86. local staticSprite = node:CreateComponent("StaticSprite2D")
  87. staticSprite.sprite = cache:GetResource("Sprite2D", "Urho2D/Aster.png")
  88. local body = node:CreateComponent("RigidBody2D")
  89. body.bodyType = BT_DYNAMIC
  90. local shape = node:CreateComponent("CollisionPolygon2D")
  91. shape:SetVertices{Vector2(-0.8, -0.3), Vector2(0.5, -0.8), Vector2(0.8, -0.3), Vector2(0.8, 0.5), Vector2(0.5, 0.9), Vector2(-0.5, 0.7)}
  92. shape.density = 1 -- Set shape density (kilograms per meter squared)
  93. shape.friction = 0.3 -- Set friction
  94. shape.restitution = 0 -- Set restitution (no bounce)
  95. -- Create a ConstraintDistance2D
  96. CreateFlag("ConstraintDistance2D", -4.97, 3) -- Display Text3D flag
  97. local boxNode = box:Clone()
  98. local ballNode = ball:Clone()
  99. local ballBody = ballNode:GetComponent("RigidBody2D")
  100. boxNode.position = Vector3(-4.5, 2, 0)
  101. ballNode.position = Vector3(-3, 2, 0)
  102. local constraintDistance = boxNode:CreateComponent("ConstraintDistance2D") -- Apply ConstraintDistance2D to box
  103. constraintDistance.otherBody = ballBody -- Constrain ball to box
  104. constraintDistance.ownerBodyAnchor = boxNode.position2D
  105. constraintDistance.otherBodyAnchor = ballNode.position2D
  106. -- Make the constraint soft (comment to make it rigid, which is its basic behavior)
  107. constraintDistance.frequencyHz = 4
  108. constraintDistance.dampingRatio = 0.5
  109. -- Create a ConstraintFriction2D ********** Not functional. From Box2d samples it seems that 2 anchors are required, Urho2D only provides 1, needs investigation ***********
  110. CreateFlag("ConstraintFriction2D", 0.03, 1) -- Display Text3D flag
  111. local boxNode = box:Clone()
  112. local ballNode = ball:Clone()
  113. boxNode.position = Vector3(0.5, 0, 0)
  114. ballNode.position = Vector3(1.5, 0, 0)
  115. local constraintFriction = boxNode:CreateComponent("ConstraintFriction2D") -- Apply ConstraintDistance2D to box
  116. constraintFriction.otherBody = ballNode:GetComponent("RigidBody2D") -- Constraint ball to box
  117. constraintFriction.ownerBodyAnchor = boxNode.position2D
  118. --constraintFriction.otherBodyAnchor = ballNode.position2D
  119. --constraintFriction.maxForce = 10 -- ballBody.mass * gravity
  120. --constraintDistance.maxTorque = 10 -- ballBody.mass * radius * gravity
  121. -- Create a ConstraintGear2D
  122. CreateFlag("ConstraintGear2D", -4.97, -1) -- Display Text3D flag
  123. local baseNode = box:Clone()
  124. baseNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
  125. baseNode.position = Vector3(-3.7, -2.5, 0)
  126. local ball1Node = ball:Clone()
  127. ball1Node.position = Vector3(-4.5, -2, 0)
  128. local ball1Body = ball1Node:GetComponent("RigidBody2D")
  129. local ball2Node = ball:Clone()
  130. ball2Node.position = Vector3(-3, -2, 0)
  131. local ball2Body = ball2Node:GetComponent("RigidBody2D")
  132. local gear1 = baseNode:CreateComponent("ConstraintRevolute2D") -- Apply constraint to baseBox
  133. gear1.otherBody = ball1Body -- Constrain ball1 to baseBox
  134. gear1.anchor = ball1Node.position2D
  135. local gear2 = baseNode:CreateComponent("ConstraintRevolute2D") -- Apply constraint to baseBox
  136. gear2.otherBody = ball2Body -- Constrain ball2 to baseBox
  137. gear2.anchor = ball2Node.position2D
  138. local constraintGear = ball1Node:CreateComponent("ConstraintGear2D") -- Apply constraint to ball1
  139. constraintGear.otherBody = ball2Body -- Constrain ball2 to ball1
  140. constraintGear.ownerConstraint = gear1
  141. constraintGear.otherConstraint = gear2
  142. constraintGear.ratio=1
  143. ball1Body:ApplyAngularImpulse(0.015, true) -- Animate
  144. -- Create a vehicle from a compound of 2 ConstraintWheel2Ds
  145. CreateFlag("ConstraintWheel2Ds compound", -2.45, -1) -- Display Text3D flag
  146. local car = box:Clone()
  147. car.scale = Vector3(4, 1, 0)
  148. car.position = Vector3(-1.2, -2.3, 0)
  149. car:GetComponent("StaticSprite2D").orderInLayer = 0 -- Draw car on top of the wheels (set to -1 to draw below)
  150. local ball1Node = ball:Clone()
  151. ball1Node.position = Vector3(-1.6, -2.5, 0)
  152. local ball2Node = ball:Clone()
  153. ball2Node.position = Vector3(-0.8, -2.5, 0)
  154. local wheel1 = car:CreateComponent("ConstraintWheel2D")
  155. wheel1.otherBody = ball1Node:GetComponent("RigidBody2D")
  156. wheel1.anchor = ball1Node.position2D
  157. wheel1.axis = Vector2(0, 1)
  158. wheel1.maxMotorTorque = 20
  159. wheel1.frequencyHz = 4
  160. wheel1.dampingRatio = 0.4
  161. local wheel2 = car:CreateComponent("ConstraintWheel2D")
  162. wheel2.otherBody = ball2Node:GetComponent("RigidBody2D")
  163. wheel2.anchor = ball2Node.position2D
  164. wheel2.axis = Vector2(0, 1)
  165. wheel2.maxMotorTorque = 10
  166. wheel2.frequencyHz = 4
  167. wheel2.dampingRatio = 0.4
  168. -- Create a ConstraintMotor2D
  169. CreateFlag("ConstraintMotor2D", 2.53, -1) -- Display Text3D flag
  170. local boxNode = box:Clone()
  171. boxNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
  172. local ballNode = ball:Clone()
  173. boxNode.position = Vector3(3.8, -2.1, 0)
  174. ballNode.position = Vector3(3.8, -1.5, 0)
  175. constraintMotor = boxNode:CreateComponent("ConstraintMotor2D")
  176. constraintMotor.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
  177. constraintMotor.linearOffset = Vector2(0, 0.8) -- Set ballNode position relative to boxNode position = (0,0)
  178. constraintMotor.angularOffset = 0.1
  179. constraintMotor.maxForce = 5
  180. constraintMotor.maxTorque = 10
  181. constraintMotor.correctionFactor = 1
  182. constraintMotor.collideConnected = true -- doesn't work
  183. -- Create a ConstraintMouse2D is demonstrated in HandleMouseButtonDown() function. It is used to "grasp" the sprites with the mouse.
  184. CreateFlag("ConstraintMouse2D", 0.03, -1) -- Display Text3D flag
  185. -- Create a ConstraintPrismatic2D
  186. CreateFlag("ConstraintPrismatic2D", 2.53, 3) -- Display Text3D flag
  187. local boxNode = box:Clone()
  188. boxNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
  189. local ballNode = ball:Clone()
  190. boxNode.position = Vector3(3.3, 2.5, 0)
  191. ballNode.position = Vector3(4.3, 2, 0)
  192. local constraintPrismatic = boxNode:CreateComponent("ConstraintPrismatic2D")
  193. constraintPrismatic.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
  194. constraintPrismatic.axis = Vector2(1, 1) -- Slide from [0,0] to [1,1]
  195. constraintPrismatic.anchor = Vector2(4, 2)
  196. constraintPrismatic.lowerTranslation = -1
  197. constraintPrismatic.upperTranslation = 0.5
  198. constraintPrismatic.enableLimit = true
  199. constraintPrismatic.maxMotorForce = 1
  200. constraintPrismatic.motorSpeed = 0
  201. -- Create a ConstraintPulley2D
  202. CreateFlag("ConstraintPulley2D", 0.03, 3) -- Display Text3D flag
  203. local boxNode = box:Clone()
  204. local ballNode = ball:Clone()
  205. boxNode.position = Vector3(0.5, 2, 0)
  206. ballNode.position = Vector3(2, 2, 0)
  207. local constraintPulley = boxNode:CreateComponent("ConstraintPulley2D") -- Apply constraint to box
  208. constraintPulley.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
  209. constraintPulley.ownerBodyAnchor = boxNode.position2D
  210. constraintPulley.otherBodyAnchor = ballNode.position2D
  211. constraintPulley.ownerBodyGroundAnchor = Vector2(boxNode.position.x, boxNode.position.y + 1)
  212. constraintPulley.otherBodyGroundAnchor = Vector2(ballNode.position.x, ballNode.position.y + 1)
  213. constraintPulley.ratio = 1 -- Weight ratio between ownerBody and otherBody
  214. -- Create a ConstraintRevolute2D
  215. CreateFlag("ConstraintRevolute2D", -2.45, 3) -- Display Text3D flag
  216. local boxNode = box:Clone()
  217. boxNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
  218. local ballNode = ball:Clone()
  219. boxNode.position = Vector3(-2, 1.5, 0)
  220. ballNode.position = Vector3(-1, 2, 0)
  221. local constraintRevolute = boxNode:CreateComponent("ConstraintRevolute2D") -- Apply constraint to box
  222. constraintRevolute.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
  223. constraintRevolute.anchor = Vector2(-1, 1.5)
  224. constraintRevolute.lowerAngle = -1 -- In radians
  225. constraintRevolute.upperAngle = 0.5 -- In radians
  226. constraintRevolute.enableLimit = true
  227. constraintRevolute.maxMotorTorque = 10
  228. constraintRevolute.motorSpeed = 0
  229. constraintRevolute.enableMotor = true
  230. -- Create a ConstraintRope2D
  231. CreateFlag("ConstraintRope2D", -4.97, 1) -- Display Text3D flag
  232. local boxNode = box:Clone()
  233. boxNode:GetComponent("RigidBody2D").bodyType = BT_STATIC
  234. local ballNode = ball:Clone()
  235. boxNode.position = Vector3(-3.7, 0.7, 0)
  236. ballNode.position = Vector3(-4.5, 0, 0)
  237. local constraintRope = boxNode:CreateComponent("ConstraintRope2D")
  238. constraintRope.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
  239. constraintRope.ownerBodyAnchor = Vector2(0, -0.5) -- Offset from box (OwnerBody) : the rope is rigid from OwnerBody center to this ownerBodyAnchor
  240. constraintRope.maxLength = 0.9 -- Rope length
  241. constraintRope.collideConnected = true
  242. -- Create a ConstraintWeld2D
  243. CreateFlag("ConstraintWeld2D", -2.45, 1) -- Display Text3D flag
  244. local boxNode = box:Clone()
  245. local ballNode = ball:Clone()
  246. boxNode.position = Vector3(-0.5, 0, 0)
  247. ballNode.position = Vector3(-2, 0, 0)
  248. local constraintWeld = boxNode:CreateComponent("ConstraintWeld2D")
  249. constraintWeld.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
  250. constraintWeld.anchor = boxNode.position2D
  251. constraintWeld.frequencyHz = 4
  252. constraintWeld.dampingRatio = 0.5
  253. -- ConstraintWheel2D
  254. CreateFlag("ConstraintWheel2D", 2.53, 1) -- Display Text3D flag
  255. local boxNode = box:Clone()
  256. local ballNode = ball:Clone()
  257. boxNode.position = Vector3(3.8, 0, 0)
  258. ballNode.position = Vector3(3.8, 0.9, 0)
  259. local constraintWheel = boxNode:CreateComponent("ConstraintWheel2D")
  260. constraintWheel.otherBody = ballNode:GetComponent("RigidBody2D") -- Constrain ball to box
  261. constraintWheel.anchor = ballNode.position2D
  262. constraintWheel.axis = Vector2(0, 1)
  263. constraintWheel.enableMotor = true
  264. constraintWheel.maxMotorTorque = 1
  265. constraintWheel.motorSpeed = 0
  266. constraintWheel.frequencyHz = 4
  267. constraintWheel.dampingRatio = 0.5
  268. constraintWheel.collideConnected = true -- doesn't work
  269. end
  270. function CreateFlag(text, x, y) -- Used to create Tex3D flags
  271. local flagNode = scene_:CreateChild("Flag")
  272. flagNode.position = Vector3(x, y, 0)
  273. local flag3D = flagNode:CreateComponent("Text3D") -- We use Text3D in order to make the text affected by zoom (so that it sticks to 2D)
  274. flag3D.text = text
  275. flag3D:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  276. end
  277. function CreateInstructions()
  278. -- Construct new Text object, set string to display and font to use
  279. local instructionText = ui.root:CreateChild("Text")
  280. instructionText:SetText("Use WASD keys and mouse to move, Use PageUp PageDown to zoom.\n Space to toggle debug geometry and joints - F5 to save the scene.")
  281. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  282. instructionText.textAlignment = HA_CENTER -- Center rows in relation to each other
  283. -- Position the text relative to the screen center
  284. instructionText.horizontalAlignment = HA_CENTER
  285. instructionText.verticalAlignment = VA_CENTER
  286. instructionText:SetPosition(0, ui.root.height / 4)
  287. end
  288. function MoveCamera(timeStep)
  289. if ui.focusElement ~= nil then return end -- Do not move if the UI has a focused element (the console)
  290. local MOVE_SPEED = 4 -- Movement speed as world units per second
  291. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  292. if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0, 1, 0) * MOVE_SPEED * timeStep) end
  293. if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0, -1, 0) * MOVE_SPEED * timeStep) end
  294. if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1, 0, 0) * MOVE_SPEED * timeStep) end
  295. if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1, 0, 0) * MOVE_SPEED * timeStep) end
  296. if input:GetKeyDown(KEY_PAGEUP) then camera.zoom = camera.zoom * 1.01 end -- Zoom In
  297. if input:GetKeyDown(KEY_PAGEDOWN) then camera.zoom = camera.zoom * 0.99 end -- Zoom Out
  298. end
  299. function SubscribeToEvents()
  300. SubscribeToEvent("Update", "HandleUpdate")
  301. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  302. SubscribeToEvent("MouseButtonDown", "HandleMouseButtonDown")
  303. if touchEnabled then SubscribeToEvent("TouchBegin", "HandleTouchBegin3") end
  304. -- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  305. UnsubscribeFromEvent("SceneUpdate")
  306. end
  307. function HandleUpdate(eventType, eventData)
  308. local timestep = eventData:GetFloat("TimeStep")
  309. MoveCamera(timestep) -- Move the camera according to frame's time step
  310. if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end -- Toggle debug geometry with space
  311. if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Constraints.xml") end -- Save scene
  312. end
  313. function HandlePostRenderUpdate(eventType, eventData)
  314. if drawDebug then physicsWorld:DrawDebugGeometry() end
  315. end
  316. function HandleMouseButtonDown(eventType, eventData)
  317. local rigidBody = physicsWorld:GetRigidBody(input.mousePosition.x, input.mousePosition.y) -- Raycast for RigidBody2Ds to pick
  318. if rigidBody ~= nil then
  319. pickedNode = rigidBody:GetNode()
  320. local staticSprite = pickedNode:GetComponent("StaticSprite2D")
  321. staticSprite.color = Color(1, 0, 0, 1) -- Temporary modify color of the picked sprite
  322. -- ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with the mouse
  323. local constraintMouse = pickedNode:CreateComponent("ConstraintMouse2D")
  324. constraintMouse.target = GetMousePositionXY()
  325. constraintMouse.maxForce = 1000 * rigidBody.mass
  326. constraintMouse.collideConnected = true
  327. constraintMouse.otherBody = dummyBody -- Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
  328. constraintMouse.dampingRatio = 0
  329. end
  330. SubscribeToEvent("MouseMove", "HandleMouseMove")
  331. SubscribeToEvent("MouseButtonUp", "HandleMouseButtonUp")
  332. end
  333. function HandleMouseButtonUp(eventType, eventData)
  334. if pickedNode ~= nil then
  335. local staticSprite = pickedNode:GetComponent("StaticSprite2D")
  336. staticSprite.color = Color(1, 1, 1, 1) -- Restore picked sprite color
  337. pickedNode:RemoveComponent("ConstraintMouse2D") -- Remove temporary constraint
  338. pickedNode = nil
  339. end
  340. UnsubscribeFromEvent("MouseMove")
  341. UnsubscribeFromEvent("MouseButtonUp")
  342. end
  343. function GetMousePositionXY()
  344. local screenPoint = Vector3(input.mousePosition.x / graphics.width, input.mousePosition.y / graphics.height, 0)
  345. local worldPoint = camera:ScreenToWorldPoint(screenPoint)
  346. return Vector2(worldPoint.x, worldPoint.y)
  347. end
  348. function HandleMouseMove(eventType, eventData)
  349. if pickedNode ~= nil then
  350. local constraintMouse = pickedNode:GetComponent("ConstraintMouse2D")
  351. constraintMouse.target = GetMousePositionXY()
  352. end
  353. end
  354. function HandleTouchBegin3(eventType, eventData)
  355. local rigidBody = physicsWorld:GetRigidBody(eventData:GetInt("X"), eventData:GetInt("Y")) -- Raycast for RigidBody2Ds to pick
  356. if rigidBody ~= nil then
  357. pickedNode = rigidBody:GetNode()
  358. local staticSprite = pickedNode:GetComponent("StaticSprite2D")
  359. staticSprite.color = Color(1, 0, 0, 1) -- Temporary modify color of the picked sprite
  360. local rigidBody = pickedNode:GetComponent("RigidBody2D")
  361. -- ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with touch
  362. local constraintMouse = pickedNode:CreateComponent("ConstraintMouse2D")
  363. constraintMouse.target = camera:ScreenToWorldPoint(Vector3(eventData:GetInt("X") / graphics.width, eventData:GetInt("Y") / graphics.height, 0))
  364. constraintMouse.maxForce = 1000 * rigidBody.mass
  365. constraintMouse.collideConnected = true
  366. constraintMouse.otherBody = dummyBody -- Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
  367. constraintMouse.dampingRatio = 0
  368. end
  369. SubscribeToEvent("TouchMove", "HandleTouchMove3")
  370. SubscribeToEvent("TouchEnd", "HandleTouchEnd3")
  371. end
  372. function HandleTouchMove3(eventType, eventData)
  373. if pickedNode ~= nil then
  374. local constraintMouse = pickedNode:GetComponent("ConstraintMouse2D")
  375. constraintMouse.target = camera:ScreenToWorldPoint(Vector3(eventData:GetInt("X") / graphics.width, eventData:GetInt("Y") / graphics.height, 0))
  376. end
  377. end
  378. function HandleTouchEnd3(eventType, eventData)
  379. if pickedNode ~= nil then
  380. local staticSprite = pickedNode:GetComponent("StaticSprite2D")
  381. staticSprite.color = Color(1, 1, 1, 1) -- Restore picked sprite color
  382. pickedNode:RemoveComponent("ConstraintMouse2D") -- Remove temporary constraint
  383. pickedNode = nil
  384. end
  385. UnsubscribeFromEvent("TouchMove")
  386. UnsubscribeFromEvent("TouchEnd")
  387. end
  388. -- Create XML patch instructions for screen joystick layout specific to this sample app
  389. function GetScreenJoystickPatchString()
  390. return
  391. "<patch>" ..
  392. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  393. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" ..
  394. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  395. " <element type=\"Text\">" ..
  396. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  397. " <attribute name=\"Text\" value=\"PAGEUP\" />" ..
  398. " </element>" ..
  399. " </add>" ..
  400. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  401. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" ..
  402. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  403. " <element type=\"Text\">" ..
  404. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  405. " <attribute name=\"Text\" value=\"PAGEDOWN\" />" ..
  406. " </element>" ..
  407. " </add>" ..
  408. "</patch>"
  409. end