Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question Is this the best way to Freeze Position?

Discussion in 'Physics for ECS' started by KANIYO, Feb 11, 2024.

  1. KANIYO

    KANIYO

    Joined:
    Nov 12, 2020
    Posts:
    28
    RigidBody has FreezePosition in Constraints, but Physics For ECS does not.
    Is this the best way to do it?


    Code (CSharp):
    1.     public class ConstraintsPositionAuthoring : MonoBehaviour
    2.     {
    3.         public bool3 linerConstrainedAxes; // x, y, z
    4.  
    5.  
    6.         public class Baker : Baker<ConstraintsPositionAuthoring>
    7.         {
    8.             public override void Bake(ConstraintsPositionAuthoring authoring)
    9.             {
    10.                 // The entity will be moved
    11.                 var entity = GetEntity(TransformUsageFlags.Dynamic);
    12.  
    13.                 // create PhysicsJoint
    14.                 Constraint constraint = new()
    15.                 {
    16.                     ConstrainedAxes = authoring.linerConstrainedAxes,
    17.                     Type = ConstraintType.Linear,
    18.                     Min = 0,
    19.                     Max = 0,
    20.                     SpringFrequency = Constraint.DefaultSpringFrequency,
    21.                     SpringDamping = Constraint.DefaultSpringDamping
    22.                 };
    23.  
    24.                 FixedList512Bytes<Constraint> fixedList = new(){
    25.                     constraint
    26.                 };
    27.  
    28.                 PhysicsJoint physicsJoint = new();
    29.                 physicsJoint.SetConstraints(fixedList);
    30.  
    31.  
    32.                 // create PhysicsConstrainedBodyPair
    33.                 PhysicsConstrainedBodyPair bodyPair = new(entity, Entity.Null, false);
    34.  
    35.                 // add them
    36.                 AddComponent(entity, physicsJoint);
    37.                 AddComponent(entity, bodyPair);
    38.             }
    39.         }
    40.     }
    memo: As for Rotation, it is possible by setting Infinity to Inertia Tensor in the Override Default Mass Distribution in the Advanced section of Physics BodyAuthoring.
     
  2. daniel-holz

    daniel-holz

    Unity Technologies

    Joined:
    Sep 17, 2021
    Posts:
    329
    You could simply reset the corresponding position components in your rigid body to whatever you want them to be using a system, updated in AfterPhysicsSystemGroup. That would be more efficient and more precise than using a joint.