Urho2DConstraints.cpp 29 KB

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