32_Urho2DConstraints.as 25 KB

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