Urho2DConstraints.cpp 29 KB

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