PrismaticJointLimitsManager.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. © Siemens AG, 2017-2018
  3. Author: Suzannah Smith (suzannah.smith@siemens.com)
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. <http://www.apache.org/licenses/LICENSE-2.0>.
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. using UnityEngine;
  15. namespace RosSharp
  16. {
  17. public class PrismaticJointLimitsManager : MonoBehaviour
  18. {
  19. public float PositionLimitMin;
  20. public float PositionLimitMax;
  21. public float Tolerance = 0.01f;
  22. private ConfigurableJoint configurableJoint;
  23. private float referencePosition;
  24. private void Awake()
  25. {
  26. configurableJoint = GetComponent<ConfigurableJoint>();
  27. referencePosition = Vector3.Dot(transform.localPosition, configurableJoint.axis);
  28. }
  29. private void FixedUpdate()
  30. {
  31. ApplyLimits();
  32. }
  33. private void OnValidate()
  34. {
  35. if (PositionLimitMax < PositionLimitMin)
  36. PositionLimitMax = PositionLimitMin;
  37. }
  38. private void ApplyLimits()
  39. {
  40. float position = Vector3.Dot(transform.localPosition, configurableJoint.axis) - referencePosition;
  41. if (position - PositionLimitMin < Tolerance)
  42. {
  43. configurableJoint.xMotion = ConfigurableJointMotion.Limited;
  44. configurableJoint.linearLimit = UpdateLimit(configurableJoint.linearLimit, -PositionLimitMin);
  45. }
  46. else if (PositionLimitMax - position < Tolerance)
  47. {
  48. configurableJoint.xMotion = ConfigurableJointMotion.Limited;
  49. configurableJoint.linearLimit = UpdateLimit(configurableJoint.linearLimit, PositionLimitMax);
  50. }
  51. else
  52. {
  53. configurableJoint.xMotion = ConfigurableJointMotion.Free;
  54. }
  55. }
  56. private static SoftJointLimit UpdateLimit(SoftJointLimit softJointLimit, float limit)
  57. {
  58. softJointLimit.limit = limit;
  59. return softJointLimit;
  60. }
  61. public void InitializeLimits(Urdf.Joint.Limit limit)
  62. {
  63. PositionLimitMax = (float)limit.upper;
  64. PositionLimitMin = (float)limit.lower;
  65. }
  66. }
  67. }