ConstraintGear2D.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Context.h"
  5. #include "../Physics2D/ConstraintGear2D.h"
  6. #include "../Physics2D/PhysicsUtils2D.h"
  7. #include "../Physics2D/RigidBody2D.h"
  8. #include "../DebugNew.h"
  9. namespace Urho3D
  10. {
  11. extern const char* PHYSICS2D_CATEGORY;
  12. ConstraintGear2D::ConstraintGear2D(Context* context) :
  13. Constraint2D(context)
  14. {
  15. }
  16. ConstraintGear2D::~ConstraintGear2D() = default;
  17. void ConstraintGear2D::RegisterObject(Context* context)
  18. {
  19. context->RegisterFactory<ConstraintGear2D>(PHYSICS2D_CATEGORY);
  20. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, true, AM_DEFAULT);
  21. URHO3D_ACCESSOR_ATTRIBUTE("Ratio", GetRatio, SetRatio, 0.0f, AM_DEFAULT);
  22. URHO3D_COPY_BASE_ATTRIBUTES(Constraint2D);
  23. }
  24. void ConstraintGear2D::SetOwnerConstraint(Constraint2D* constraint)
  25. {
  26. if (constraint == ownerConstraint_)
  27. return;
  28. if (ownerConstraint_)
  29. ownerConstraint_->SetAttachedConstraint(nullptr);
  30. ownerConstraint_ = constraint;
  31. if (ownerConstraint_)
  32. ownerConstraint_->SetAttachedConstraint(this);
  33. RecreateJoint();
  34. MarkNetworkUpdate();
  35. }
  36. void ConstraintGear2D::SetOtherConstraint(Constraint2D* constraint)
  37. {
  38. WeakPtr<Constraint2D> constraintPtr(constraint);
  39. if (constraintPtr == otherConstraint_)
  40. return;
  41. if (otherConstraint_)
  42. otherConstraint_->SetAttachedConstraint(nullptr);
  43. otherConstraint_ = constraintPtr;
  44. if (otherConstraint_)
  45. otherConstraint_->SetAttachedConstraint(this);
  46. RecreateJoint();
  47. MarkNetworkUpdate();
  48. }
  49. void ConstraintGear2D::SetRatio(float ratio)
  50. {
  51. if (ratio == jointDef_.ratio)
  52. return;
  53. jointDef_.ratio = ratio;
  54. if (joint_)
  55. static_cast<b2GearJoint*>(joint_)->SetRatio(ratio);
  56. else
  57. RecreateJoint();
  58. MarkNetworkUpdate();
  59. }
  60. b2JointDef* ConstraintGear2D::GetJointDef()
  61. {
  62. if (!ownerBody_ || !otherBody_)
  63. return nullptr;
  64. b2Body* bodyA = ownerBody_->GetBody();
  65. b2Body* bodyB = otherBody_->GetBody();
  66. if (!bodyA || !bodyB)
  67. return nullptr;
  68. if (!ownerConstraint_ || !otherConstraint_)
  69. return nullptr;
  70. b2Joint* jointA = ownerConstraint_->GetJoint();
  71. b2Joint* jointB = otherConstraint_->GetJoint();
  72. if (!jointA || !jointB)
  73. return nullptr;
  74. InitializeJointDef(&jointDef_);
  75. jointDef_.joint1 = jointA;
  76. jointDef_.joint2 = jointB;
  77. return &jointDef_;
  78. }
  79. }