Urho2DConstraints.cpp 27 KB

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