Urho2DConstraints.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. //
  2. // Copyright (c) 2008-2022 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/Container/Vector.h>
  23. #include <Urho3D/Core/CoreEvents.h>
  24. #include <Urho3D/Engine/Engine.h>
  25. #include <Urho3D/Graphics/Camera.h>
  26. #include <Urho3D/Graphics/DebugRenderer.h>
  27. #include <Urho3D/Graphics/Graphics.h>
  28. #include <Urho3D/Graphics/Octree.h>
  29. #include <Urho3D/Graphics/Renderer.h>
  30. #include <Urho3D/Graphics/Zone.h>
  31. #include <Urho3D/Input/Input.h>
  32. #include <Urho3D/IO/FileSystem.h>
  33. #include <Urho3D/Physics2D/CollisionBox2D.h>
  34. #include <Urho3D/Physics2D/CollisionCircle2D.h>
  35. #include <Urho3D/Physics2D/CollisionEdge2D.h>
  36. #include <Urho3D/Physics2D/CollisionPolygon2D.h>
  37. #include <Urho3D/Physics2D/ConstraintDistance2D.h>
  38. #include <Urho3D/Physics2D/ConstraintFriction2D.h>
  39. #include <Urho3D/Physics2D/ConstraintGear2D.h>
  40. #include <Urho3D/Physics2D/ConstraintMotor2D.h>
  41. #include <Urho3D/Physics2D/ConstraintMouse2D.h>
  42. #include <Urho3D/Physics2D/ConstraintPrismatic2D.h>
  43. #include <Urho3D/Physics2D/ConstraintPulley2D.h>
  44. #include <Urho3D/Physics2D/ConstraintRevolute2D.h>
  45. #include <Urho3D/Physics2D/ConstraintWeld2D.h>
  46. #include <Urho3D/Physics2D/ConstraintWheel2D.h>
  47. #include <Urho3D/Physics2D/PhysicsWorld2D.h>
  48. #include <Urho3D/Physics2D/RigidBody2D.h>
  49. #include <Urho3D/Resource/ResourceCache.h>
  50. #include <Urho3D/Scene/Scene.h>
  51. #include <Urho3D/Scene/SceneEvents.h>
  52. #include <Urho3D/UI/Font.h>
  53. #include <Urho3D/UI/Text.h>
  54. #include <Urho3D/UI/Text3D.h>
  55. #include <Urho3D/Urho2D/Drawable2D.h>
  56. #include <Urho3D/Urho2D/Sprite2D.h>
  57. #include <Urho3D/Urho2D/StaticSprite2D.h>
  58. #include "Urho2DConstraints.h"
  59. #include <Urho3D/DebugNew.h>
  60. URHO3D_DEFINE_APPLICATION_MAIN(Urho2DConstraints)
  61. Node* pickedNode;
  62. RigidBody2D* dummyBody;
  63. Urho2DConstraints::Urho2DConstraints(Context* context) :
  64. Sample(context)
  65. {
  66. }
  67. void Urho2DConstraints::Start()
  68. {
  69. // Execute base class startup
  70. Sample::Start();
  71. // Create the scene content
  72. CreateScene();
  73. // Enable OS cursor
  74. GetSubsystem<Input>()->SetMouseVisible(true);
  75. // Create the UI content
  76. CreateInstructions();
  77. // Hook up to the frame update events
  78. SubscribeToEvents();
  79. // Set the mouse mode to use in the sample
  80. Sample::InitMouseMode(MM_FREE);
  81. }
  82. void Urho2DConstraints::CreateScene()
  83. {
  84. scene_ = new Scene(context_);
  85. scene_->CreateComponent<Octree>();
  86. scene_->CreateComponent<DebugRenderer>();
  87. auto* 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. auto* 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. auto* 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. auto* edgeBody = edgeNode->CreateComponent<RigidBody2D>();
  110. if (!dummyBody)
  111. dummyBody = edgeBody; // Mark first edge as dummy body (used by mouse pick)
  112. auto* 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. auto* 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. auto* 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. auto* boxSprite = box->CreateComponent<StaticSprite2D>();
  129. boxSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Box.png"));
  130. auto* boxBody = box->CreateComponent<RigidBody2D>();
  131. boxBody->SetBodyType(BT_DYNAMIC);
  132. boxBody->SetLinearDamping(0.0f);
  133. boxBody->SetAngularDamping(0.0f);
  134. auto* 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. auto* ballSprite = ball->CreateComponent<StaticSprite2D>();
  143. ballSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Ball.png"));
  144. auto* ballBody = ball->CreateComponent<RigidBody2D>();
  145. ballBody->SetBodyType(BT_DYNAMIC);
  146. ballBody->SetLinearDamping(0.0f);
  147. ballBody->SetAngularDamping(0.0f);
  148. auto* 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. auto* polygonSprite = polygon->CreateComponent<StaticSprite2D>();
  158. polygonSprite->SetSprite(cache->GetResource<Sprite2D>("Urho2D/Aster.png"));
  159. auto* polygonBody = polygon->CreateComponent<RigidBody2D>();
  160. polygonBody->SetBodyType(BT_DYNAMIC);
  161. auto* 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. auto* 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. auto* 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->SetMinLength(constraintDistance->GetLength() - 1.f);
  186. constraintDistance->SetMaxLength(constraintDistance->GetLength() + 1.f);
  187. constraintDistance->SetLinearStiffness(4.0f, 0.5f);
  188. // Create a ConstraintFriction2D ********** Not functional. From Box2d samples it seems that 2 anchors are required, Urho2D only provides 1, needs investigation ***********
  189. CreateFlag("ConstraintFriction2D", 0.03f, 1.0f); // Display Text3D flag
  190. Node* boxFrictionNode = box->Clone();
  191. Node* ballFrictionNode = ball->Clone();
  192. boxFrictionNode->SetPosition(Vector3(0.5f, 0.0f, 0.0f));
  193. ballFrictionNode->SetPosition(Vector3(1.5f, 0.0f, 0.0f));
  194. auto* constraintFriction = boxFrictionNode->CreateComponent<ConstraintFriction2D>(); // Apply ConstraintDistance2D to box
  195. constraintFriction->SetOtherBody(ballFrictionNode->GetComponent<RigidBody2D>()); // Constraint ball to box
  196. //constraintFriction->SetOwnerBodyAnchor(boxNode->GetPosition2D());
  197. //constraintFriction->SetOtherBodyAnchor(ballNode->GetPosition2D());
  198. //constraintFriction->SetMaxForce(10.0f); // ballBody.mass * gravity
  199. //constraintDistance->SetMaxTorque(10.0f); // ballBody.mass * radius * gravity
  200. // Create a ConstraintGear2D
  201. CreateFlag("ConstraintGear2D", -4.97f, -1.0f); // Display Text3D flag
  202. Node* baseNode = box->Clone();
  203. auto* tempBody = baseNode->GetComponent<RigidBody2D>(); // Get body to make it static
  204. tempBody->SetBodyType(BT_STATIC);
  205. baseNode->SetPosition(Vector3(-3.7f, -2.5f, 0.0f));
  206. Node* ball1Node = ball->Clone();
  207. ball1Node->SetPosition(Vector3(-4.5f, -2.0f, 0.0f));
  208. auto* ball1Body = ball1Node->GetComponent<RigidBody2D>();
  209. Node* ball2Node = ball->Clone();
  210. ball2Node->SetPosition(Vector3(-3.0f, -2.0f, 0.0f));
  211. auto* ball2Body = ball2Node->GetComponent<RigidBody2D>();
  212. auto* gear1 = baseNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to baseBox
  213. gear1->SetOtherBody(ball1Body); // Constrain ball1 to baseBox
  214. gear1->SetAnchor(ball1Node->GetPosition2D());
  215. auto* gear2 = baseNode->CreateComponent<ConstraintRevolute2D>(); // Apply constraint to baseBox
  216. gear2->SetOtherBody(ball2Body); // Constrain ball2 to baseBox
  217. gear2->SetAnchor(ball2Node->GetPosition2D());
  218. auto* constraintGear = ball1Node->CreateComponent<ConstraintGear2D>(); // Apply constraint to ball1
  219. constraintGear->SetOtherBody(ball2Body); // Constrain ball2 to ball1
  220. constraintGear->SetOwnerConstraint(gear1);
  221. constraintGear->SetOtherConstraint(gear2);
  222. constraintGear->SetRatio(1.0f);
  223. ball1Body->ApplyAngularImpulse(0.015f, true); // Animate
  224. // Create a vehicle from a compound of 2 ConstraintWheel2Ds
  225. CreateFlag("ConstraintWheel2Ds compound", -2.45f, -1.0f); // Display Text3D flag
  226. Node* car = box->Clone();
  227. car->SetScale(Vector3(4.0f, 1.0f, 0.0f));
  228. car->SetPosition(Vector3(-1.2f, -2.3f, 0.0f));
  229. auto* tempSprite = car->GetComponent<StaticSprite2D>(); // Get car Sprite in order to draw it on top
  230. tempSprite->SetOrderInLayer(0); // Draw car on top of the wheels (set to -1 to draw below)
  231. Node* ball1WheelNode = ball->Clone();
  232. ball1WheelNode->SetPosition(Vector3(-1.6f, -2.5f, 0.0f));
  233. Node* ball2WheelNode = ball->Clone();
  234. ball2WheelNode->SetPosition(Vector3(-0.8f, -2.5f, 0.0f));
  235. auto* wheel1 = car->CreateComponent<ConstraintWheel2D>();
  236. wheel1->SetOtherBody(ball1WheelNode->GetComponent<RigidBody2D>());
  237. wheel1->SetAnchor(ball1WheelNode->GetPosition2D());
  238. wheel1->SetAxis(Vector2(0.0f, 1.0f));
  239. wheel1->SetMaxMotorTorque(20.0f);
  240. wheel1->SetLinearStiffness(4.0f, 0.4f);
  241. auto* 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->SetLinearStiffness(4.0f, 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. auto* 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. auto* 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. auto* 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. auto* 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 ConstraintWeld2D
  313. CreateFlag("ConstraintWeld2D", -2.45f, 1.0f); // Display Text3D flag
  314. Node* boxWeldNode = box->Clone();
  315. Node* ballWeldNode = ball->Clone();
  316. boxWeldNode->SetPosition(Vector3(-0.5f, 0.0f, 0.0f));
  317. ballWeldNode->SetPosition(Vector3(-2.0f, 0.0f, 0.0f));
  318. auto* constraintWeld = boxWeldNode->CreateComponent<ConstraintWeld2D>();
  319. constraintWeld->SetOtherBody(ballWeldNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  320. constraintWeld->SetAnchor(boxWeldNode->GetPosition2D());
  321. constraintWeld->SetAngularStiffness(4.0f, 0.5f);
  322. // Create a ConstraintWheel2D
  323. CreateFlag("ConstraintWheel2D", 2.53f, 1.0f); // Display Text3D flag
  324. Node* boxWheelNode = box->Clone();
  325. Node* ballWheelNode = ball->Clone();
  326. boxWheelNode->SetPosition(Vector3(3.8f, 0.0f, 0.0f));
  327. ballWheelNode->SetPosition(Vector3(3.8f, 0.9f, 0.0f));
  328. auto* constraintWheel = boxWheelNode->CreateComponent<ConstraintWheel2D>();
  329. constraintWheel->SetOtherBody(ballWheelNode->GetComponent<RigidBody2D>()); // Constrain ball to box
  330. constraintWheel->SetAnchor(ballWheelNode->GetPosition2D());
  331. constraintWheel->SetAxis(Vector2(0.0f, 1.0f));
  332. constraintWheel->SetEnableMotor(true);
  333. constraintWheel->SetMaxMotorTorque(1.0f);
  334. constraintWheel->SetMotorSpeed(0.0f);
  335. constraintWheel->SetLinearStiffness(4.0f, 0.5f);
  336. //constraintWheel->SetCollideConnected(true); // doesn't work
  337. }
  338. void Urho2DConstraints::CreateFlag(const String& text, float x, float y) // Used to create Tex3D flags
  339. {
  340. Node* flagNode = scene_->CreateChild("Flag");
  341. flagNode->SetPosition(Vector3(x, y, 0.0f));
  342. auto* flag3D = flagNode->CreateComponent<Text3D>(); // We use Text3D in order to make the text affected by zoom (so that it sticks to 2D)
  343. flag3D->SetText(text);
  344. auto* cache = GetSubsystem<ResourceCache>();
  345. flag3D->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  346. }
  347. void Urho2DConstraints::CreateInstructions()
  348. {
  349. auto* cache = GetSubsystem<ResourceCache>();
  350. auto* ui = GetSubsystem<UI>();
  351. // Construct new Text object, set string to display and font to use
  352. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  353. 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.");
  354. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  355. instructionText->SetTextAlignment(HA_CENTER); // Center rows in relation to each other
  356. // Position the text relative to the screen center
  357. instructionText->SetHorizontalAlignment(HA_CENTER);
  358. instructionText->SetVerticalAlignment(VA_CENTER);
  359. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  360. }
  361. void Urho2DConstraints::MoveCamera(float timeStep)
  362. {
  363. // Do not move if the UI has a focused element (the console)
  364. if (GetSubsystem<UI>()->GetFocusElement())
  365. return;
  366. auto* input = GetSubsystem<Input>();
  367. // Movement speed as world units per second
  368. const float MOVE_SPEED = 4.0f;
  369. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  370. if (input->GetKeyDown(KEY_W))
  371. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  372. if (input->GetKeyDown(KEY_S))
  373. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  374. if (input->GetKeyDown(KEY_A))
  375. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  376. if (input->GetKeyDown(KEY_D))
  377. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  378. if (input->GetKeyDown(KEY_PAGEUP))
  379. camera_->SetZoom(camera_->GetZoom() * 1.01f);
  380. if (input->GetKeyDown(KEY_PAGEDOWN))
  381. camera_->SetZoom(camera_->GetZoom() * 0.99f);
  382. }
  383. void Urho2DConstraints::SubscribeToEvents()
  384. {
  385. // Subscribe HandleUpdate() function for processing update events
  386. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Urho2DConstraints, HandleUpdate));
  387. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry
  388. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Urho2DConstraints, HandlePostRenderUpdate));
  389. // Subscribe to mouse click
  390. SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(Urho2DConstraints, HandleMouseButtonDown));
  391. // Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
  392. UnsubscribeFromEvent(E_SCENEUPDATE);
  393. if (touchEnabled_)
  394. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(Urho2DConstraints, HandleTouchBegin3));
  395. }
  396. void Urho2DConstraints::HandleUpdate(StringHash eventType, VariantMap& eventData)
  397. {
  398. using namespace Update;
  399. // Take the frame time step, which is stored as a float
  400. float timeStep = eventData[P_TIMESTEP].GetFloat();
  401. // Move the camera, scale movement with time step
  402. MoveCamera(timeStep);
  403. auto* input = GetSubsystem<Input>();
  404. // Toggle physics debug geometry with space
  405. if (input->GetKeyPress(KEY_SPACE))
  406. drawDebug_ = !drawDebug_;
  407. // Save scene
  408. if (input->GetKeyPress(KEY_F5))
  409. {
  410. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/Constraints.xml", FILE_WRITE);
  411. scene_->SaveXML(saveFile);
  412. }
  413. }
  414. void Urho2DConstraints::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  415. {
  416. auto* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
  417. if (drawDebug_) physicsWorld->DrawDebugGeometry();
  418. }
  419. void Urho2DConstraints::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  420. {
  421. auto* input = GetSubsystem<Input>();
  422. auto* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
  423. RigidBody2D* rigidBody = physicsWorld->GetRigidBody(input->GetMousePosition().x_, input->GetMousePosition().y_); // Raycast for RigidBody2Ds to pick
  424. if (rigidBody)
  425. {
  426. pickedNode = rigidBody->GetNode();
  427. //log.Info(pickedNode.name);
  428. auto* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
  429. staticSprite->SetColor(Color(1.0f, 0.0f, 0.0f, 1.0f)); // Temporary modify color of the picked sprite
  430. // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with the mouse
  431. auto* constraintMouse = pickedNode->CreateComponent<ConstraintMouse2D>();
  432. constraintMouse->SetTarget(GetMousePositionXY());
  433. constraintMouse->SetMaxForce(1000 * rigidBody->GetMass());
  434. constraintMouse->SetCollideConnected(true);
  435. constraintMouse->SetOtherBody(dummyBody); // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
  436. constraintMouse->SetLinearStiffness(5.0f, 0.7f);
  437. }
  438. SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(Urho2DConstraints, HandleMouseMove));
  439. SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(Urho2DConstraints, HandleMouseButtonUp));
  440. }
  441. void Urho2DConstraints::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  442. {
  443. if (pickedNode)
  444. {
  445. auto* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
  446. staticSprite->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f)); // Restore picked sprite color
  447. pickedNode->RemoveComponent<ConstraintMouse2D>(); // Remove temporary constraint
  448. pickedNode = nullptr;
  449. }
  450. UnsubscribeFromEvent(E_MOUSEMOVE);
  451. UnsubscribeFromEvent(E_MOUSEBUTTONUP);
  452. }
  453. Vector2 Urho2DConstraints::GetMousePositionXY()
  454. {
  455. auto* input = GetSubsystem<Input>();
  456. auto* graphics = GetSubsystem<Graphics>();
  457. Vector3 screenPoint = Vector3((float)input->GetMousePosition().x_ / graphics->GetWidth(), (float)input->GetMousePosition().y_ / graphics->GetHeight(), 0.0f);
  458. Vector3 worldPoint = camera_->ScreenToWorldPoint(screenPoint);
  459. return Vector2(worldPoint.x_, worldPoint.y_);
  460. }
  461. void Urho2DConstraints::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  462. {
  463. if (pickedNode)
  464. {
  465. auto* constraintMouse = pickedNode->GetComponent<ConstraintMouse2D>();
  466. constraintMouse->SetTarget(GetMousePositionXY());
  467. }
  468. }
  469. void Urho2DConstraints::HandleTouchBegin3(StringHash eventType, VariantMap& eventData)
  470. {
  471. auto* graphics = GetSubsystem<Graphics>();
  472. auto* physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
  473. using namespace TouchBegin;
  474. RigidBody2D* rigidBody = physicsWorld->GetRigidBody(eventData[P_X].GetInt(), eventData[P_Y].GetInt()); // Raycast for RigidBody2Ds to pick
  475. if (rigidBody)
  476. {
  477. pickedNode = rigidBody->GetNode();
  478. auto* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
  479. staticSprite->SetColor(Color(1.0f, 0.0f, 0.0f, 1.0f)); // Temporary modify color of the picked sprite
  480. auto* rigidBody = pickedNode->GetComponent<RigidBody2D>();
  481. // Create a ConstraintMouse2D - Temporary apply this constraint to the pickedNode to allow grasping and moving with touch
  482. auto* constraintMouse = pickedNode->CreateComponent<ConstraintMouse2D>();
  483. Vector3 pos = camera_->ScreenToWorldPoint(Vector3((float)eventData[P_X].GetInt() / graphics->GetWidth(), (float)eventData[P_Y].GetInt() / graphics->GetHeight(), 0.0f));
  484. constraintMouse->SetTarget(Vector2(pos.x_, pos.y_));
  485. constraintMouse->SetMaxForce(1000 * rigidBody->GetMass());
  486. constraintMouse->SetCollideConnected(true);
  487. constraintMouse->SetOtherBody(dummyBody); // Use dummy body instead of rigidBody. It's better to create a dummy body automatically in ConstraintMouse2D
  488. constraintMouse->SetLinearStiffness(5.0f, 0.7f);
  489. }
  490. SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(Urho2DConstraints, HandleTouchMove3));
  491. SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(Urho2DConstraints, HandleTouchEnd3));
  492. }
  493. void Urho2DConstraints::HandleTouchMove3(StringHash eventType, VariantMap& eventData)
  494. {
  495. if (pickedNode)
  496. {
  497. auto* graphics = GetSubsystem<Graphics>();
  498. auto* constraintMouse = pickedNode->GetComponent<ConstraintMouse2D>();
  499. using namespace TouchMove;
  500. Vector3 pos = camera_->ScreenToWorldPoint(Vector3(float(eventData[P_X].GetInt()) / graphics->GetWidth(), float(eventData[P_Y].GetInt()) / graphics->GetHeight(), 0.0f));
  501. constraintMouse->SetTarget(Vector2(pos.x_, pos.y_));
  502. }
  503. }
  504. void Urho2DConstraints::HandleTouchEnd3(StringHash eventType, VariantMap& eventData)
  505. {
  506. if (pickedNode)
  507. {
  508. auto* staticSprite = pickedNode->GetComponent<StaticSprite2D>();
  509. staticSprite->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f)); // Restore picked sprite color
  510. pickedNode->RemoveComponent<ConstraintMouse2D>(); // Remove temporary constraint
  511. pickedNode = nullptr;
  512. }
  513. UnsubscribeFromEvent(E_TOUCHMOVE);
  514. UnsubscribeFromEvent(E_TOUCHEND);
  515. }