Constraints2D.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Container/Vector.h>
  24. #include <Atomic/Core/CoreEvents.h>
  25. #include <Atomic/Engine/Engine.h>
  26. #include <Atomic/Graphics/Camera.h>
  27. #include <Atomic/Graphics/DebugRenderer.h>
  28. #include <Atomic/Graphics/Graphics.h>
  29. #include <Atomic/Graphics/Octree.h>
  30. #include <Atomic/Graphics/Renderer.h>
  31. #include <Atomic/Graphics/Zone.h>
  32. #include <Atomic/Input/Input.h>
  33. #include <Atomic/IO/FileSystem.h>
  34. #include <Atomic/Resource/ResourceCache.h>
  35. #include <Atomic/Scene/Scene.h>
  36. #include <Atomic/Scene/SceneEvents.h>
  37. #include <Atomic/Atomic2D/CollisionBox2D.h>
  38. #include <Atomic/Atomic2D/CollisionCircle2D.h>
  39. #include <Atomic/Atomic2D/CollisionEdge2D.h>
  40. #include <Atomic/Atomic2D/CollisionPolygon2D.h>
  41. #include <Atomic/Atomic2D/ConstraintDistance2D.h>
  42. #include <Atomic/Atomic2D/ConstraintFriction2D.h>
  43. #include <Atomic/Atomic2D/ConstraintGear2D.h>
  44. #include <Atomic/Atomic2D/ConstraintMotor2D.h>
  45. #include <Atomic/Atomic2D/ConstraintMouse2D.h>
  46. #include <Atomic/Atomic2D/ConstraintPrismatic2D.h>
  47. #include <Atomic/Atomic2D/ConstraintPulley2D.h>
  48. #include <Atomic/Atomic2D/ConstraintRevolute2D.h>
  49. #include <Atomic/Atomic2D/ConstraintRope2D.h>
  50. #include <Atomic/Atomic2D/ConstraintWeld2D.h>
  51. #include <Atomic/Atomic2D/ConstraintWheel2D.h>
  52. #include <Atomic/Atomic2D/Drawable2D.h>
  53. #include <Atomic/Atomic2D/PhysicsWorld2D.h>
  54. #include <Atomic/Atomic2D/RigidBody2D.h>
  55. #include <Atomic/Atomic2D/Sprite2D.h>
  56. #include <Atomic/Atomic2D/StaticSprite2D.h>
  57. #include "Constraints2D.h"
  58. #include <Atomic/DebugNew.h>
  59. Node* pickedNode;
  60. RigidBody2D* dummyBody;
  61. Constraints2D::Constraints2D(Context* context) :
  62. Sample(context)
  63. {
  64. }
  65. void Constraints2D::Start()
  66. {
  67. // Execute base class startup
  68. Sample::Start();
  69. // Create the scene content
  70. CreateScene();
  71. // Enable OS cursor
  72. GetSubsystem<Input>()->SetMouseVisible(true);
  73. // Create the UI content
  74. CreateInstructions();
  75. // Hook up to the frame update events
  76. SubscribeToEvents();
  77. // Set the mouse mode to use in the sample
  78. Sample::InitMouseMode(MM_FREE);
  79. }
  80. void Constraints2D::CreateScene()
  81. {
  82. scene_ = new Scene(context_);
  83. scene_->CreateComponent<Octree>();
  84. scene_->CreateComponent<DebugRenderer>();
  85. PhysicsWorld2D* physicsWorld = scene_->CreateComponent<PhysicsWorld2D>(); // Create 2D physics world component
  86. physicsWorld->SetDrawJoint(true); // Display the joints (Note that DrawDebugGeometry() must be set to true to acually draw the joints)
  87. drawDebug_ = true; // Set DrawDebugGeometry() to true
  88. // Create camera
  89. cameraNode_ = scene_->CreateChild("Camera");
  90. // Set camera's position
  91. cameraNode_->SetPosition(Vector3(0.0f, 0.0f, 0.0f)); // Note that Z setting is discarded; use camera.zoom instead (see MoveCamera() below for example)
  92. camera_ = cameraNode_->CreateComponent<Camera>();
  93. camera_->SetOrthographic(true);
  94. Graphics* graphics = GetSubsystem<Graphics>();
  95. camera_->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
  96. camera_->SetZoom(1.2f * Min((float)graphics->GetWidth() / 1280.0f, (float)graphics->GetHeight() / 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)
  97. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  98. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, camera_));
  99. Renderer* renderer = GetSubsystem<Renderer>();
  100. renderer->SetViewport(0, viewport);
  101. Zone* zone = renderer->GetDefaultZone();
  102. zone->SetFogColor(Color(0.1f, 0.1f, 0.1f)); // Set background color for the scene
  103. // Create 4x3 grid
  104. for (unsigned i = 0; i<5; ++i)
  105. {
  106. Node* edgeNode = scene_->CreateChild("VerticalEdge");
  107. RigidBody2D* edgeBody = edgeNode->CreateComponent<RigidBody2D>();
  108. if (!dummyBody)
  109. dummyBody = edgeBody; // Mark first edge as dummy body (used by mouse pick)
  110. CollisionEdge2D* edgeShape = edgeNode->CreateComponent<CollisionEdge2D>();
  111. edgeShape->SetVertices(Vector2(i*2.5f -5.0f, -3.0f), Vector2(i*2.5f -5.0f, 3.0f));
  112. edgeShape->SetFriction(0.5f); // Set friction
  113. }
  114. for (unsigned j = 0; j<4; ++j)
  115. {
  116. Node* edgeNode = scene_->CreateChild("HorizontalEdge");
  117. /*RigidBody2D* edgeBody = */edgeNode->CreateComponent<RigidBody2D>();
  118. CollisionEdge2D* edgeShape = edgeNode->CreateComponent<CollisionEdge2D>();
  119. edgeShape->SetVertices(Vector2(-5.0f, j*2.0f -3.0f), Vector2(5.0f, j*2.0f -3.0f));
  120. edgeShape->SetFriction(0.5f); // Set friction
  121. }
  122. ResourceCache* cache = GetSubsystem<ResourceCache>();
  123. // Create a box (will be cloned later)
  124. Node* box = scene_->CreateChild("Box");
  125. box->SetPosition(Vector3(0.8f, -2.0f, 0.0f));
  126. StaticSprite2D* boxSprite = box->CreateComponent<StaticSprite2D>();
  127. boxSprite->SetSprite(cache->GetResource<Sprite2D>("Atomic2D/Box.png"));
  128. RigidBody2D* boxBody = box->CreateComponent<RigidBody2D>();
  129. boxBody->SetBodyType(BT_DYNAMIC);
  130. boxBody->SetLinearDamping(0.0f);
  131. boxBody->SetAngularDamping(0.0f);
  132. CollisionBox2D* shape = box->CreateComponent<CollisionBox2D>(); // Create box shape
  133. shape->SetSize(Vector2(0.32f, 0.32f)); // Set size
  134. shape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
  135. shape->SetFriction(0.5f); // Set friction
  136. shape->SetRestitution(0.1f); // Set restitution (slight bounce)
  137. // Create a ball (will be cloned later)
  138. Node* ball = scene_->CreateChild("Ball");
  139. ball->SetPosition(Vector3(1.8f, -2.0f, 0.0f));
  140. StaticSprite2D* ballSprite = ball->CreateComponent<StaticSprite2D>();
  141. ballSprite->SetSprite(cache->GetResource<Sprite2D>("Atomic2D/Ball.png"));
  142. RigidBody2D* ballBody = ball->CreateComponent<RigidBody2D>();
  143. ballBody->SetBodyType(BT_DYNAMIC);
  144. ballBody->SetLinearDamping(0.0f);
  145. ballBody->SetAngularDamping(0.0f);
  146. CollisionCircle2D* ballShape = ball->CreateComponent<CollisionCircle2D>(); // Create circle shape
  147. ballShape->SetRadius(0.16f); // Set radius
  148. ballShape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
  149. ballShape->SetFriction(0.5f); // Set friction
  150. ballShape->SetRestitution(0.6f); // Set restitution: make it bounce
  151. // Create a polygon
  152. Node* polygon = scene_->CreateChild("Polygon");
  153. polygon->SetPosition(Vector3(1.6f, -2.0f, 0.0f));
  154. polygon->SetScale(0.7f);
  155. StaticSprite2D* polygonSprite = polygon->CreateComponent<StaticSprite2D>();
  156. polygonSprite->SetSprite(cache->GetResource<Sprite2D>("Atomic2D/Aster.png"));
  157. RigidBody2D* polygonBody = polygon->CreateComponent<RigidBody2D>();
  158. polygonBody->SetBodyType(BT_DYNAMIC);
  159. CollisionPolygon2D* polygonShape = polygon->CreateComponent<CollisionPolygon2D>();
  160. // TODO: create from PODVector<Vector2> using SetVertices()
  161. polygonShape->SetVertexCount(6); // Set number of vertices (mandatory when using SetVertex())
  162. polygonShape->SetVertex(0, Vector2(-0.8f, -0.3f));
  163. polygonShape->SetVertex(1, Vector2(0.5f, -0.8f));
  164. polygonShape->SetVertex(2, Vector2(0.8f, -0.3f));
  165. polygonShape->SetVertex(3, Vector2(0.8f, 0.5f));
  166. polygonShape->SetVertex(4, Vector2(0.5f, 0.9f));
  167. polygonShape->SetVertex(5, Vector2(-0.5f, 0.7f));
  168. polygonShape->SetDensity(1.0f); // Set shape density (kilograms per meter squared)
  169. polygonShape->SetFriction(0.3f); // Set friction
  170. polygonShape->SetRestitution(0.0f); // Set restitution (no bounce)
  171. // Create a ConstraintDistance2D
  172. CreateFlag("ConstraintDistance2D", -4.97f, 3.0f); // Display Text3D flag
  173. Node* boxDistanceNode = box->Clone();
  174. Node* ballDistanceNode = ball->Clone();
  175. RigidBody2D* ballDistanceBody = ballDistanceNode->GetComponent<RigidBody2D>();
  176. boxDistanceNode->SetPosition(Vector3(-4.5f, 2.0f, 0.0f));
  177. ballDistanceNode->SetPosition(Vector3(-3.0f, 2.0f, 0.0f));
  178. ConstraintDistance2D* constraintDistance = boxDistanceNode->CreateComponent<ConstraintDistance2D>(); // Apply ConstraintDistance2D to box
  179. constraintDistance->SetOtherBody(ballDistanceBody); // Constrain ball to box
  180. constraintDistance->SetOwnerBodyAnchor(boxDistanceNode->GetPosition2D());
  181. constraintDistance->SetOtherBodyAnchor(ballDistanceNode->GetPosition2D());
  182. // Make the constraint soft (comment to make it rigid, which is its basic behavior)
  183. constraintDistance->SetFrequencyHz(4.0f);
  184. constraintDistance->SetDampingRatio(0.5f);
  185. // Create a ConstraintFriction2D ********** Not functional. From Box2d samples it seems that 2 anchors are required, Urho2D only provides 1, needs investigation ***********
  186. CreateFlag("ConstraintFriction2D", 0.03f, 1.0f); // Display Text3D flag
  187. Node* boxFrictionNode = box->Clone();
  188. Node* ballFrictionNode = ball->Clone();
  189. boxFrictionNode->SetPosition(Vector3(0.5f, 0.0f, 0.0f));
  190. ballFrictionNode->SetPosition(Vector3(1.5f, 0.0f, 0.0f));
  191. ConstraintFriction2D* constraintFriction = boxFrictionNode->CreateComponent<ConstraintFriction2D>(); // Apply ConstraintDistance2D to box
  192. constraintFriction->SetOtherBody(ballFrictionNode->GetComponent<RigidBody2D>()); // Constraint ball to box
  193. //constraintFriction->SetOwnerBodyAnchor(boxNode->GetPosition2D());
  194. //constraintFriction->SetOtherBodyAnchor(ballNode->GetPosition2D());
  195. //constraintFriction->SetMaxForce(10.0f); // ballBody.mass * gravity
  196. //constraintDistance->SetMaxTorque(10.0f); // ballBody.mass * radius * gravity
  197. // Create a ConstraintGear2D
  198. CreateFlag("ConstraintGear2D", -4.97f, -1.0f); // Display Text3D flag
  199. Node* baseNode = box->Clone();
  200. RigidBody2D* tempBody = baseNode->GetComponent<RigidBody2D>(); // Get body to make it static
  201. tempBody->SetBodyType(BT_STATIC);
  202. baseNode->SetPosition(Vector3(-3.7f, -2.5f, 0.0f));
  203. Node* ball1Node = ball->Clone();
  204. ball1Node->SetPosition(Vector3(-4.5f, -2.0f, 0.0f));
  205. RigidBody2D* ball1Body = ball1Node->GetComponent<RigidBody2D>();
  206. Node* ball2Node = ball->Clone();
  207. ball2Node->SetPosition(Vector3(-3.0f, -2.0f, 0.0f));
  208. RigidBody2D* ball2Body = ball2Node->GetComponent<RigidBody2D>();
  209. ConstraintRevolute2D* gear1 = baseNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to baseBox
  210. gear1->SetOtherBody(ball1Body); // Constrain ball1 to baseBox
  211. gear1->SetAnchor(ball1Node->GetPosition2D());
  212. ConstraintRevolute2D* gear2 = baseNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to baseBox
  213. gear2->SetOtherBody(ball2Body); // Constrain ball2 to baseBox
  214. gear2->SetAnchor(ball2Node->GetPosition2D());
  215. ConstraintGear2D* constraintGear = ball1Node->CreateComponent<ConstraintGear2D>(); // Apply constraint to ball1
  216. constraintGear->SetOtherBody(ball2Body); // Constrain ball2 to ball1
  217. constraintGear->SetOwnerConstraint(gear1);
  218. constraintGear->SetOtherConstraint(gear2);
  219. constraintGear->SetRatio(1.0f);
  220. ball1Body->ApplyAngularImpulse(0.015f, true); // Animate
  221. // Create a vehicle from a compound of 2 ConstraintWheel2Ds
  222. CreateFlag("ConstraintWheel2Ds compound", -2.45f, -1.0f); // Display Text3D flag
  223. Node* car = box->Clone();
  224. car->SetScale(Vector3(4.0f, 1.0f, 0.0f));
  225. car->SetPosition(Vector3(-1.2f, -2.3f, 0.0f));
  226. StaticSprite2D* tempSprite = car->GetComponent<StaticSprite2D>(); // Get car Sprite in order to draw it on top
  227. tempSprite->SetOrderInLayer(0); // Draw car on top of the wheels (set to -1 to draw below)
  228. Node* ball1WheelNode = ball->Clone();
  229. ball1WheelNode->SetPosition(Vector3(-1.6f, -2.5f, 0.0f));
  230. Node* ball2WheelNode = ball->Clone();
  231. ball2WheelNode->SetPosition(Vector3(-0.8f, -2.5f, 0.0f));
  232. ConstraintWheel2D* wheel1 = car->CreateComponent<ConstraintWheel2D>();
  233. wheel1->SetOtherBody(ball1WheelNode->GetComponent<RigidBody2D>());
  234. wheel1->SetAnchor(ball1WheelNode->GetPosition2D());
  235. wheel1->SetAxis(Vector2(0.0f, 1.0f));
  236. wheel1->SetMaxMotorTorque(20.0f);
  237. wheel1->SetFrequencyHz(4.0f);
  238. wheel1->SetDampingRatio(0.4f);
  239. ConstraintWheel2D* wheel2 = car->CreateComponent<ConstraintWheel2D>();
  240. wheel2->SetOtherBody(ball2WheelNode->GetComponent<RigidBody2D>());
  241. wheel2->SetAnchor(ball2WheelNode->GetPosition2D());
  242. wheel2->SetAxis(Vector2(0.0f, 1.0f));
  243. wheel2->SetMaxMotorTorque(10.0f);
  244. wheel2->SetFrequencyHz(4.0f);
  245. wheel2->SetDampingRatio(0.4f);
  246. // ConstraintMotor2D
  247. CreateFlag("ConstraintMotor2D", 2.53f, -1.0f); // Display Text3D flag
  248. Node* boxMotorNode = box->Clone();
  249. tempBody = boxMotorNode->GetComponent<RigidBody2D>(); // Get body to make it static
  250. tempBody->SetBodyType(BT_STATIC);
  251. Node* ballMotorNode = ball->Clone();
  252. boxMotorNode->SetPosition(Vector3(3.8f, -2.1f, 0.0f));
  253. ballMotorNode->SetPosition(Vector3(3.8f, -1.5f, 0.0f));
  254. ConstraintMotor2D* constraintMotor = boxMotorNode->CreateComponent<ConstraintMotor2D>();
  255. constraintMotor->SetOtherBody(ballMotorNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  256. constraintMotor->SetLinearOffset(Vector2(0.0f, 0.8f)); // Set ballNode position relative to boxNode position = (0,0)
  257. constraintMotor->SetAngularOffset(0.1f);
  258. constraintMotor->SetMaxForce(5.0f);
  259. constraintMotor->SetMaxTorque(10.0f);
  260. constraintMotor->SetCorrectionFactor(1.0f);
  261. constraintMotor->SetCollideConnected(true); // doesn't work
  262. // ConstraintMouse2D is demonstrated in HandleMouseButtonDown() function. It is used to "grasp" the sprites with the mouse.
  263. CreateFlag("ConstraintMouse2D", 0.03f, -1.0f); // Display Text3D flag
  264. // Create a ConstraintPrismatic2D
  265. CreateFlag("ConstraintPrismatic2D", 2.53f, 3.0f); // Display Text3D flag
  266. Node* boxPrismaticNode = box->Clone();
  267. tempBody = boxPrismaticNode->GetComponent<RigidBody2D>(); // Get body to make it static
  268. tempBody->SetBodyType(BT_STATIC);
  269. Node* ballPrismaticNode = ball->Clone();
  270. boxPrismaticNode->SetPosition(Vector3(3.3f, 2.5f, 0.0f));
  271. ballPrismaticNode->SetPosition(Vector3(4.3f, 2.0f, 0.0f));
  272. ConstraintPrismatic2D* constraintPrismatic = boxPrismaticNode->CreateComponent<ConstraintPrismatic2D>();
  273. constraintPrismatic->SetOtherBody(ballPrismaticNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  274. constraintPrismatic->SetAxis(Vector2(1.0f, 1.0f)); // Slide from [0,0] to [1,1]
  275. constraintPrismatic->SetAnchor(Vector2(4.0f, 2.0f));
  276. constraintPrismatic->SetLowerTranslation(-1.0f);
  277. constraintPrismatic->SetUpperTranslation(0.5f);
  278. constraintPrismatic->SetEnableLimit(true);
  279. constraintPrismatic->SetMaxMotorForce(1.0f);
  280. constraintPrismatic->SetMotorSpeed(0.0f);
  281. // ConstraintPulley2D
  282. CreateFlag("ConstraintPulley2D", 0.03f, 3.0f); // Display Text3D flag
  283. Node* boxPulleyNode = box->Clone();
  284. Node* ballPulleyNode = ball->Clone();
  285. boxPulleyNode->SetPosition(Vector3(0.5f, 2.0f, 0.0f));
  286. ballPulleyNode->SetPosition(Vector3(2.0f, 2.0f, 0.0f));
  287. ConstraintPulley2D* constraintPulley = boxPulleyNode->CreateComponent<ConstraintPulley2D>(); // Apply constraint to box
  288. constraintPulley->SetOtherBody(ballPulleyNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  289. constraintPulley->SetOwnerBodyAnchor(boxPulleyNode->GetPosition2D());
  290. constraintPulley->SetOtherBodyAnchor(ballPulleyNode->GetPosition2D());
  291. constraintPulley->SetOwnerBodyGroundAnchor(boxPulleyNode->GetPosition2D() + Vector2(0.0f, 1.0f));
  292. constraintPulley->SetOtherBodyGroundAnchor(ballPulleyNode->GetPosition2D() + Vector2(0.0f, 1.0f));
  293. constraintPulley->SetRatio(1.0); // Weight ratio between ownerBody and otherBody
  294. // Create a ConstraintRevolute2D
  295. CreateFlag("ConstraintRevolute2D", -2.45f, 3.0f); // Display Text3D flag
  296. Node* boxRevoluteNode = box->Clone();
  297. tempBody = boxRevoluteNode->GetComponent<RigidBody2D>(); // Get body to make it static
  298. tempBody->SetBodyType(BT_STATIC);
  299. Node* ballRevoluteNode = ball->Clone();
  300. boxRevoluteNode->SetPosition(Vector3(-2.0f, 1.5f, 0.0f));
  301. ballRevoluteNode->SetPosition(Vector3(-1.0f, 2.0f, 0.0f));
  302. ConstraintRevolute2D* constraintRevolute = boxRevoluteNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to box
  303. constraintRevolute->SetOtherBody(ballRevoluteNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  304. constraintRevolute->SetAnchor(Vector2(-1.0f, 1.5f));
  305. constraintRevolute->SetLowerAngle(-1.0f); // In radians
  306. constraintRevolute->SetUpperAngle(0.5f); // In radians
  307. constraintRevolute->SetEnableLimit(true);
  308. constraintRevolute->SetMaxMotorTorque(10.0f);
  309. constraintRevolute->SetMotorSpeed(0.0f);
  310. constraintRevolute->SetEnableMotor(true);
  311. // Create a ConstraintRope2D
  312. CreateFlag("ConstraintRope2D", -4.97f, 1.0f); // Display Text3D flag
  313. Node* boxRopeNode = box->Clone();
  314. tempBody = boxRopeNode->GetComponent<RigidBody2D>();
  315. tempBody->SetBodyType(BT_STATIC);
  316. Node* ballRopeNode = ball->Clone();
  317. boxRopeNode->SetPosition(Vector3(-3.7f, 0.7f, 0.0f));
  318. ballRopeNode->SetPosition(Vector3(-4.5f, 0.0f, 0.0f));
  319. ConstraintRope2D* constraintRope = boxRopeNode->CreateComponent<ConstraintRope2D>();
  320. constraintRope->SetOtherBody(ballRopeNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  321. constraintRope->SetOwnerBodyAnchor(Vector2(0.0f, -0.5f)); // Offset from box (OwnerBody) : the rope is rigid from OwnerBody center to this ownerBodyAnchor
  322. constraintRope->SetMaxLength(0.9f); // Rope length
  323. constraintRope->SetCollideConnected(true);
  324. // Create a ConstraintWeld2D
  325. CreateFlag("ConstraintWeld2D", -2.45f, 1.0f); // Display Text3D flag
  326. Node* boxWeldNode = box->Clone();
  327. Node* ballWeldNode = ball->Clone();
  328. boxWeldNode->SetPosition(Vector3(-0.5f, 0.0f, 0.0f));
  329. ballWeldNode->SetPosition(Vector3(-2.0f, 0.0f, 0.0f));
  330. ConstraintWeld2D* constraintWeld = boxWeldNode->CreateComponent<ConstraintWeld2D>();
  331. constraintWeld->SetOtherBody(ballWeldNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  332. constraintWeld->SetAnchor(boxWeldNode->GetPosition2D());
  333. constraintWeld->SetFrequencyHz(4.0f);
  334. constraintWeld->SetDampingRatio(0.5f);
  335. // Create a ConstraintWheel2D
  336. CreateFlag("ConstraintWheel2D", 2.53f, 1.0f); // Display Text3D flag
  337. Node* boxWheelNode = box->Clone();
  338. Node* ballWheelNode = ball->Clone();
  339. boxWheelNode->SetPosition(Vector3(3.8f, 0.0f, 0.0f));
  340. ballWheelNode->SetPosition(Vector3(3.8f, 0.9f, 0.0f));
  341. ConstraintWheel2D* constraintWheel = boxWheelNode->CreateComponent<ConstraintWheel2D>();
  342. constraintWheel->SetOtherBody(ballWheelNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  343. constraintWheel->SetAnchor(ballWheelNode->GetPosition2D());
  344. constraintWheel->SetAxis(Vector2(0.0f, 1.0f));
  345. constraintWheel->SetEnableMotor(true);
  346. constraintWheel->SetMaxMotorTorque(1.0f);
  347. constraintWheel->SetMotorSpeed(0.0f);
  348. constraintWheel->SetFrequencyHz(4.0f);
  349. constraintWheel->SetDampingRatio(0.5f);
  350. constraintWheel->SetCollideConnected(true); // doesn't work
  351. }
  352. void Constraints2D::CreateFlag(const String& text, float x, float y) // Used to create Tex3D flags
  353. {
  354. /*
  355. Node* flagNode = scene_->CreateChild("Flag");
  356. flagNode->SetPosition(Vector3(x, y, 0.0f));
  357. Text3D* flag3D = flagNode->CreateComponent<Text3D>(); // We use Text3D in order to make the text affected by zoom (so that it sticks to 2D)
  358. flag3D->SetText(text);
  359. ResourceCache* cache = GetSubsystem<ResourceCache>();
  360. flag3D->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  361. */
  362. }
  363. void Constraints2D::CreateInstructions()
  364. {
  365. SimpleCreateInstructions("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.");
  366. }
  367. void Constraints2D::MoveCamera(float timeStep)
  368. {
  369. Input* input = GetSubsystem<Input>();
  370. // Movement speed as world units per second
  371. const float MOVE_SPEED = 4.0f;
  372. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  373. if (input->GetKeyDown(KEY_W))
  374. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  375. if (input->GetKeyDown(KEY_S))
  376. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  377. if (input->GetKeyDown(KEY_A))
  378. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  379. if (input->GetKeyDown(KEY_D))
  380. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  381. if (input->GetKeyDown(KEY_PAGEUP))
  382. camera_->SetZoom(camera_->GetZoom() * 1.01f);
  383. if (input->GetKeyDown(KEY_PAGEDOWN))
  384. camera_->SetZoom(camera_->GetZoom() * 0.99f);
  385. }
  386. void Constraints2D::SubscribeToEvents()
  387. {
  388. // Subscribe HandleUpdate() function for processing update events
  389. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(Constraints2D, HandleUpdate));
  390. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry
  391. SubscribeToEvent(E_POSTRENDERUPDATE, ATOMIC_HANDLER(Constraints2D, HandlePostRenderUpdate));
  392. // Subscribe to mouse click
  393. SubscribeToEvent(E_MOUSEBUTTONDOWN, ATOMIC_HANDLER(Constraints2D, HandleMouseButtonDown));
  394. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  395. UnsubscribeFromEvent(E_SCENEUPDATE);
  396. if (touchEnabled_)
  397. SubscribeToEvent(E_TOUCHBEGIN, ATOMIC_HANDLER(Constraints2D, HandleTouchBegin3));
  398. }
  399. void Constraints2D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  400. {
  401. using namespace Update;
  402. // Take the frame time step, which is stored as a float
  403. float timeStep = eventData[P_TIMESTEP].GetFloat();
  404. // Move the camera, scale movement with time step
  405. MoveCamera(timeStep);
  406. Input* input = GetSubsystem<Input>();
  407. // Toggle physics debug geometry with space
  408. if (input->GetKeyPress(KEY_SPACE))
  409. drawDebug_ = !drawDebug_;
  410. // Save scene
  411. if (input->GetKeyPress(KEY_F5))
  412. {
  413. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/Constraints.xml", FILE_WRITE);
  414. scene_->SaveXML(saveFile);
  415. }
  416. }
  417. void Constraints2D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  418. {
  419. PhysicsWorld2D* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
  420. if (drawDebug_) physicsWorld->DrawDebugGeometry();
  421. }
  422. void Constraints2D::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  423. {
  424. Input* input = GetSubsystem<Input>();
  425. PhysicsWorld2D* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
  426. RigidBody2D* rigidBody = physicsWorld->GetRigidBody(input->GetMousePosition().x_, input->GetMousePosition().y_, M_MAX_UNSIGNED); // Raycast for RigidBody2Ds to pick
  427. if (rigidBody)
  428. {
  429. pickedNode = rigidBody->GetNode();
  430. //log.Info(pickedNode.name);
  431. StaticSprite2D* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
  432. staticSprite->SetColor(Color(1.0f, 0.0f, 0.0f, 1.0f)); // Temporary modify color of the picked sprite
  433. // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with the mouse
  434. ConstraintMouse2D* constraintMouse = pickedNode->CreateComponent<ConstraintMouse2D>();
  435. constraintMouse->SetTarget(GetMousePositionXY());
  436. constraintMouse->SetMaxForce(1000 * rigidBody->GetMass());
  437. constraintMouse->SetCollideConnected(true);
  438. constraintMouse->SetOtherBody(dummyBody); // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
  439. constraintMouse->SetDampingRatio(0.0f);
  440. }
  441. SubscribeToEvent(E_MOUSEMOVE, ATOMIC_HANDLER(Constraints2D, HandleMouseMove));
  442. SubscribeToEvent(E_MOUSEBUTTONUP, ATOMIC_HANDLER(Constraints2D, HandleMouseButtonUp));
  443. }
  444. void Constraints2D::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  445. {
  446. if (pickedNode)
  447. {
  448. StaticSprite2D* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
  449. staticSprite->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f)); // Restore picked sprite color
  450. pickedNode->RemoveComponent<ConstraintMouse2D>(); // Remove temporary constraint
  451. pickedNode = NULL;
  452. }
  453. UnsubscribeFromEvent(E_MOUSEMOVE);
  454. UnsubscribeFromEvent(E_MOUSEBUTTONUP);
  455. }
  456. Vector2 Constraints2D::GetMousePositionXY()
  457. {
  458. Input* input = GetSubsystem<Input>();
  459. Graphics* graphics = GetSubsystem<Graphics>();
  460. Vector3 screenPoint = Vector3((float)input->GetMousePosition().x_ / graphics->GetWidth(), (float)input->GetMousePosition().y_ / graphics->GetHeight(), 0.0f);
  461. Vector3 worldPoint = camera_->ScreenToWorldPoint(screenPoint);
  462. return Vector2(worldPoint.x_, worldPoint.y_);
  463. }
  464. void Constraints2D::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  465. {
  466. if (pickedNode)
  467. {
  468. ConstraintMouse2D* constraintMouse = pickedNode->GetComponent<ConstraintMouse2D>();
  469. constraintMouse->SetTarget(GetMousePositionXY());
  470. }
  471. }
  472. void Constraints2D::HandleTouchBegin3(StringHash eventType, VariantMap& eventData)
  473. {
  474. Graphics* graphics = GetSubsystem<Graphics>();
  475. PhysicsWorld2D* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
  476. using namespace TouchBegin;
  477. RigidBody2D* rigidBody = physicsWorld->GetRigidBody(Vector2((float)eventData[P_X].GetInt(), (float)eventData[P_Y].GetInt())); // Raycast for RigidBody2Ds to pick
  478. if (rigidBody)
  479. {
  480. pickedNode = rigidBody->GetNode();
  481. StaticSprite2D* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
  482. staticSprite->SetColor(Color(1.0f, 0.0f, 0.0f, 1.0f)); // Temporary modify color of the picked sprite
  483. RigidBody2D* rigidBody = pickedNode->GetComponent<RigidBody2D>();
  484. // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with touch
  485. ConstraintMouse2D* constraintMouse = pickedNode->CreateComponent<ConstraintMouse2D>();
  486. Vector3 pos = camera_->ScreenToWorldPoint(Vector3((float)eventData[P_X].GetInt() / graphics->GetWidth(), (float)eventData[P_Y].GetInt() / graphics->GetHeight(), 0.0f));
  487. constraintMouse->SetTarget(Vector2(pos.x_, pos.y_));
  488. constraintMouse->SetMaxForce(1000 * rigidBody->GetMass());
  489. constraintMouse->SetCollideConnected(true);
  490. constraintMouse->SetOtherBody(dummyBody); // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
  491. constraintMouse->SetDampingRatio(0);
  492. }
  493. SubscribeToEvent(E_TOUCHMOVE, ATOMIC_HANDLER(Constraints2D, HandleTouchMove3));
  494. SubscribeToEvent(E_TOUCHEND, ATOMIC_HANDLER(Constraints2D, HandleTouchEnd3));
  495. }
  496. void Constraints2D::HandleTouchMove3(StringHash eventType, VariantMap& eventData)
  497. {
  498. if (pickedNode)
  499. {
  500. Graphics* graphics = GetSubsystem<Graphics>();
  501. ConstraintMouse2D* constraintMouse = pickedNode->GetComponent<ConstraintMouse2D>();
  502. using namespace TouchMove;
  503. Vector3 pos = camera_->ScreenToWorldPoint(Vector3(float(eventData[P_X].GetInt()) / graphics->GetWidth(), float(eventData[P_Y].GetInt()) / graphics->GetHeight(), 0.0f));
  504. constraintMouse->SetTarget(Vector2(pos.x_, pos.y_));
  505. }
  506. }
  507. void Constraints2D::HandleTouchEnd3(StringHash eventType, VariantMap& eventData)
  508. {
  509. if (pickedNode)
  510. {
  511. StaticSprite2D* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
  512. staticSprite->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f)); // Restore picked sprite color
  513. pickedNode->RemoveComponent<ConstraintMouse2D>(); // Remove temporary constraint
  514. pickedNode = NULL;
  515. }
  516. UnsubscribeFromEvent(E_TOUCHMOVE);
  517. UnsubscribeFromEvent(E_TOUCHEND);
  518. }