PhysicsJoint CreateRigidbodyConstraints(RigidTransform offset)
        {
            var joint = new PhysicsJoint {
                BodyAFromJoint = BodyFrame.Identity,
                BodyBFromJoint = offset
            };
            var constraints = new FixedList128 <Constraint>();

            constraints.Add(new Constraint {
                ConstrainedAxes = new bool3(false, false, true),
                Type            = ConstraintType.Linear,
                Min             = 0,
                Max             = 0,
                SpringFrequency = Constraint.DefaultSpringFrequency,
                SpringDamping   = Constraint.DefaultSpringDamping
            });
            constraints.Add(new Constraint {
                ConstrainedAxes = new bool3(true, true, true),
                Type            = ConstraintType.Angular,
                Min             = 0,
                Max             = 0,
                SpringFrequency = Constraint.DefaultSpringFrequency,
                SpringDamping   = Constraint.DefaultSpringDamping
            });
            joint.SetConstraints(constraints);
            return(joint);
        }
Exemple #2
0
    private void GrabInit(PhysicsBody body, Vector3 startPos, Vector3 grabPos, Rotation rot)
    {
        if (!body.IsValid())
        {
            return;
        }

        GrabEnd();

        grabbing     = true;
        heldBody     = body;
        holdDistance = Vector3.DistanceBetween(startPos, grabPos);
        holdDistance = holdDistance.Clamp(MinTargetDistance, MaxTargetDistance);

        heldRot = rot.Inverse * heldBody.Rotation;

        holdBody.Position = grabPos;
        holdBody.Rotation = heldBody.Rotation;

        velBody.Position = grabPos;
        velBody.Rotation = heldBody.Rotation;

        heldBody.Sleeping  = false;
        heldBody.AutoSleep = false;

        holdJoint = PhysicsJoint.CreateFixed(holdBody, heldBody.WorldPoint(grabPos));
        holdJoint.SpringLinear  = new PhysicsSpring(LinearFrequency, LinearDampingRatio);
        holdJoint.SpringAngular = new PhysicsSpring(AngularFrequency, AngularDampingRatio);

        velJoint = PhysicsJoint.CreateFixed(holdBody, velBody);
        velJoint.SpringLinear  = new PhysicsSpring(LinearFrequency, LinearDampingRatio);
        velJoint.SpringAngular = new PhysicsSpring(AngularFrequency, AngularDampingRatio);
    }
 public float Speed;        // Rate of moving toward the target position
 public JointDesc(string name, float min, float max)
 {
     Name    = name; Min = min; Max = max;
     Joint   = null;
     Current = Target = 0;
     Speed   = 30;
 }
    protected override unsafe void Start()
    {
        init(); // no gravity

        Entity *entities = stackalloc Entity[2];

        entities[1] = Entity.Null;
        for (int i = 0; i < 1; i++)
        {
            CollisionFilter filter = new CollisionFilter
            {
                CollidesWith = (uint)(1 << i),
                BelongsTo    = (uint)~(1 << (1 - i))
            };
            BlobAssetReference <Collider> collider = BoxCollider.Create(
                new BoxGeometry
            {
                Center      = float3.zero,
                Orientation = quaternion.identity,
                Size        = new float3(1.0f, 0.2f, 0.2f),
                BevelRadius = 0.0f
            },
                filter, Material.Default);
            entities[i] = CreateDynamicBody(float3.zero, quaternion.identity, collider, float3.zero, new float3(0, 1 - i, 0), 1.0f);
        }

        var jointFrame = new BodyFrame {
            Axis = new float3(0, 1, 0), PerpendicularAxis = new float3(0, 0, 1)
        };
        PhysicsJoint hingeData =
            PhysicsJoint.CreateLimitedHinge(jointFrame, jointFrame, new FloatRange(-math.PI, -0.2f));

        CreateJoint(hingeData, entities[0], entities[1]);
    }
Exemple #5
0
    public static void CreateNeck(GameObject torso, GameObject head, out PhysicsJoint jointData0, out PhysicsJoint jointData1)
    {
        var   headTransform = head.GetComponent <Transform>();
        float headRadius    = 0.5f * headTransform.localScale.x;

        float3 pivotHead           = new float3(0, -headRadius, 0);
        var    torsoTransform      = torso.GetComponent <Transform>();
        var    torsoRigidTransform = new RigidTransform(torsoTransform.rotation, torsoTransform.position);

        var headRigidTransform = new RigidTransform(headTransform.rotation, headTransform.position);

        float3 pivotTorso         = math.transform(math.inverse(torsoRigidTransform), math.transform(headRigidTransform, pivotHead));
        float3 axis               = new float3(0, 1, 0);
        float3 perpendicular      = new float3(0, 0, 1);
        float  coneAngle          = math.PI / 5.0f;
        var    perpendicularAngle = new FloatRange {
            Max = math.PI
        };
        var twistAngle = new FloatRange(-math.PI / 3f, math.PI / 3f);

        var jointFrameTorso = new BodyFrame {
            Axis = axis, PerpendicularAxis = perpendicular, Position = pivotTorso
        };
        var jointFrameHead = new BodyFrame {
            Axis = axis, PerpendicularAxis = perpendicular, Position = pivotHead
        };

        PhysicsJoint.CreateRagdoll(jointFrameTorso, jointFrameHead, coneAngle, perpendicularAngle, twistAngle, out jointData0, out jointData1);
    }
Exemple #6
0
    public static void CreateWaist(GameObject torso, GameObject pelvis, out PhysicsJoint jointData0, out PhysicsJoint jointData1)
    {
        float3 pivotTorso = float3.zero;

        RigidTransform pelvisTransform = new RigidTransform(pelvis.transform.rotation, pelvis.transform.position);
        RigidTransform torsoTransform  = new RigidTransform(torso.transform.rotation, torso.transform.position);

        float3 pivotPelvis = math.transform(math.inverse(pelvisTransform), math.transform(torsoTransform, pivotTorso));
        float3 axisPelvis  = new float3(0, 0, -1);
        float3 axisTorso   = axisPelvis;

        float3 axisPerpendicular = new float3(1, 0, 0);

        float3 perpendicularPelvis = math.rotate(math.inverse(pelvisTransform), axisPerpendicular);
        float3 perpendicularTorso  = math.rotate(math.inverse(torsoTransform), axisPerpendicular);

        float coneAngle          = 0.0872665f;
        var   perpendicularAngle = new FloatRange {
            Max = math.PI
        };
        var twistAngle = new FloatRange(-0.01f, 0.1f);

        var jointFrameTorso = new BodyFrame {
            Axis = axisTorso, PerpendicularAxis = perpendicularTorso, Position = pivotTorso
        };
        var jointFramePelvis = new BodyFrame {
            Axis = axisPelvis, PerpendicularAxis = perpendicularPelvis, Position = pivotPelvis
        };

        PhysicsJoint.CreateRagdoll(jointFrameTorso, jointFramePelvis, coneAngle, perpendicularAngle, twistAngle, out jointData0, out jointData1);
    }
Exemple #7
0
    public static void CreateHip(GameObject pelvis, GameObject upperLeg, out PhysicsJoint jointData0, out PhysicsJoint jointData1)
    {
        float upperLegHeight = 2.0f * upperLeg.transform.localScale.y;

        var pelvisTransform   = new RigidTransform(pelvis.transform.rotation, pelvis.transform.position);
        var upperLegTransform = new RigidTransform(upperLeg.transform.rotation, upperLeg.transform.position);

        float3 pivotLeg    = new float3(0, upperLegHeight / 2.0f, 0);
        float3 pivotPelvis = math.transform(math.inverse(pelvisTransform), math.transform(upperLegTransform, pivotLeg));

        float3 twistAxis         = new float3(0, -1, 0);
        float3 perpendicularAxis = new float3(1, 0, 0);

        float3 twistAxisLeg    = math.rotate(math.inverse(upperLegTransform), twistAxis);
        float3 twistAxisPelvis = math.rotate(math.inverse(pelvisTransform), twistAxis);

        float3 perpendicularAxisLeg    = math.rotate(math.inverse(upperLegTransform), perpendicularAxis);
        float3 perpendicularAxisPelvis = math.rotate(math.inverse(pelvisTransform), perpendicularAxis);

        float coneAngle          = math.PI / 4.0f;
        var   perpendicularAngle = new FloatRange(math.PI / 3f, math.PI * 2f / 3f);
        var   twistAngle         = new FloatRange(-0.2f, 0.2f);

        var jointFramePelvis = new BodyFrame {
            Axis = twistAxisPelvis, PerpendicularAxis = perpendicularAxisPelvis, Position = pivotPelvis
        };
        var jointFrameLeg = new BodyFrame {
            Axis = twistAxisLeg, PerpendicularAxis = perpendicularAxisLeg, Position = pivotLeg
        };

        PhysicsJoint.CreateRagdoll(jointFramePelvis, jointFrameLeg, coneAngle, perpendicularAngle, twistAngle, out jointData0, out jointData1);
    }
Exemple #8
0
    public static PhysicsJoint CreateElbow(GameObject upperArm, GameObject lowerArm)
    {
        float upperArmLength = 2 * upperArm.transform.localScale.y;
        float lowerArmLength = 2 * lowerArm.transform.localScale.y;

        float sign = math.sign(-1.0f * upperArm.transform.position.x);

        float3 pivotUpper = new float3(-1.0f * sign * upperArmLength / 2.0f, 0, 0);
        float3 pivotLower = new float3(sign * lowerArmLength / 2.0f, 0, 0);

        pivotUpper = math.rotate(math.inverse(upperArm.transform.rotation), pivotUpper);
        pivotLower = math.rotate(math.inverse(lowerArm.transform.rotation), pivotLower);
        float3 axis          = new float3(0, 0, 1);
        float3 perpendicular = new float3(0, 1, 0);

        var jointFrameUpperArm = new BodyFrame {
            Axis = axis, PerpendicularAxis = perpendicular, Position = pivotUpper
        };
        var jointFrameLowerArm = new BodyFrame {
            Axis = axis, PerpendicularAxis = perpendicular, Position = pivotLower
        };

        return(PhysicsJoint.CreateLimitedHinge(jointFrameUpperArm, jointFrameLowerArm, new FloatRange {
            Max = 3f
        }));
    }
        public override void Create(EntityManager entityManager, GameObjectConversionSystem conversionSystem)
        {
            UpdateAuto();
            UpgradeVersionIfNecessary();
            PhysicsJoint.CreateRagdoll(
                new BodyFrame {
                Axis = TwistAxisLocal, PerpendicularAxis = PerpendicularAxisLocal, Position = PositionLocal
            },
                new BodyFrame {
                Axis = TwistAxisInConnectedEntity, PerpendicularAxis = PerpendicularAxisInConnectedEntity, Position = PositionInConnectedEntity
            },
                math.radians(MaxConeAngle),
                math.radians(new FloatRange(MinPerpendicularAngle, MaxPerpendicularAngle)),
                math.radians(new FloatRange(MinTwistAngle, MaxTwistAngle)),
                out var primaryCone,
                out var perpendicularCone
                );

            conversionSystem.World.GetOrCreateSystem <EndJointConversionSystem>().CreateJointEntities(
                this,
                GetConstrainedBodyPair(conversionSystem),
                new NativeArray <PhysicsJoint>(2, Allocator.Temp)
            {
                [0] = primaryCone, [1] = perpendicularCone
            }
                );
        }
Exemple #10
0
    public static PhysicsJoint CreateKnee(GameObject upperLeg, GameObject lowerLeg)
    {
        float upperLegHeight = 2.0f * upperLeg.transform.localScale.y;

        float3 pivotUpperLeg = new float3(0, -upperLegHeight / 2.0f, 0);

        var lowerLegTransform = new RigidTransform(lowerLeg.transform.rotation, lowerLeg.transform.position);
        var upperLegTransform = new RigidTransform(upperLeg.transform.rotation, upperLeg.transform.position);

        float3 pivotLowerLeg = math.transform(math.inverse(lowerLegTransform), math.transform(upperLegTransform, pivotUpperLeg));

        float3 axis          = new float3(1, 0, 0);
        float3 perpendicular = new float3(0, 0, 1);

        var jointFrameUpperLeg = new BodyFrame {
            Axis = axis, PerpendicularAxis = perpendicular, Position = pivotUpperLeg
        };
        var jointFrameLowerLeg = new BodyFrame {
            Axis = axis, PerpendicularAxis = perpendicular, Position = pivotLowerLeg
        };

        return(PhysicsJoint.CreateLimitedHinge(jointFrameUpperLeg, jointFrameLowerLeg, new FloatRange {
            Min = -1.2f
        }));
    }
Exemple #11
0
        public override void Simulate()
        {
            if (!Host.IsServer)
            {
                return;
            }

            using (Prediction.Off())
            {
                if (!Input.Pressed(InputButton.Attack1))
                {
                    return;
                }

                var startPos = Owner.EyePosition;
                var dir      = Owner.EyeRotation.Forward;

                var tr = Trace.Ray(startPos, startPos + dir * MaxTraceDistance)
                         .Ignore(Owner)
                         .Run();

                if (!tr.Hit)
                {
                    return;
                }

                if (!tr.Entity.IsValid())
                {
                    return;
                }

                var attached = !tr.Entity.IsWorld && tr.Body.IsValid() && tr.Body.PhysicsGroup != null && tr.Body.GetEntity().IsValid();

                if (attached && tr.Entity is not Prop)
                {
                    return;
                }

                CreateHitEffects(tr.EndPosition);

                if (tr.Entity is WheelEntity)
                {
                    // TODO: Set properties

                    return;
                }

                var ent = new WheelEntity
                {
                    Position = tr.EndPosition,
                    Rotation = Rotation.LookAt(tr.Normal) * Rotation.From(new Angles(0, 90, 0)),
                };

                ent.SetModel("models/citizen_props/wheel01.vmdl");

                ent.PhysicsBody.Mass = tr.Body.Mass;
                ent.Joint            = PhysicsJoint.CreateHinge(ent.PhysicsBody, tr.Body, tr.EndPosition, tr.Normal);
            }
        }
Exemple #12
0
        // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
        // update non-physical objects like the joint proxy objects that represent the position
        // of the joints in the scene.

        // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
        // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
        // from within the OdePhysicsScene.

        protected internal void jointMoved(PhysicsJoint joint)
        {
            // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
            SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);

            if (jointProxyObject == null)
            {
                jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
                return;
            }

            // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
            SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup

            if (trackedBody == null)
            {
                return;                      // the actor may have been deleted but the joint still lingers around a few frames waiting for deletion. during this time, trackedBody is NULL to prevent further motion of the joint proxy.
            }
            jointProxyObject.Velocity        = trackedBody.Velocity;
            jointProxyObject.AngularVelocity = trackedBody.AngularVelocity;
            switch (joint.Type)
            {
            case PhysicsJointType.Ball:
            {
                Vector3 jointAnchor = m_scene.PhysicsScene.GetJointAnchor(joint);
                Vector3 proxyPos    = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
                jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos, true);         // schedules the entire group for a terse update
            }
            break;

            case PhysicsJointType.Hinge:
            {
                Vector3 jointAnchor = m_scene.PhysicsScene.GetJointAnchor(joint);

                // Normally, we would just ask the physics scene to return the axis for the joint.
                // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
                // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
                // Therefore the following call does not always work:
                //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);

                // instead we compute the joint orientation by saving the original joint orientation
                // relative to one of the jointed bodies, and applying this transformation
                // to the current position of the jointed bodies (the tracked body) to compute the
                // current joint orientation.

                if (joint.TrackedBodyName == null)
                {
                    jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
                }

                Vector3    proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
                Quaternion q        = trackedBody.RotationOffset * joint.LocalRotation;

                jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos, true); // schedules the entire group for a terse update
                jointProxyObject.ParentGroup.UpdateGroupRotationR(q);             // schedules the entire group for a terse update
            }
            break;
            }
        }
    protected override void Start()
    {
        base.Start();

        BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.BoxCollider.Create(new BoxGeometry
        {
            Center      = float3.zero,
            Orientation = quaternion.identity,
            Size        = new float3(0.25f),
            BevelRadius = 0.0f
        });

        var manager = DefaultWorld.EntityManager;

        // Add a dynamic body constrained to the world that will die
        // Once the dynamic body is destroyed the joint will be invalid
        {
            // Create a dynamic body
            float3 pivotWorld = new float3(-2f, 0, 0);
            Entity body       = CreateDynamicBody(pivotWorld, quaternion.identity, collider, float3.zero, float3.zero, 1.0f);

            // create extra dynamic body to trigger havok sync after the first one is destroyed
            CreateDynamicBody(pivotWorld * 2.0f, quaternion.identity, collider, float3.zero, float3.zero, 1.0f);

            // add timeout on dynamic body after 15 frames.
            manager.AddComponentData(body, new LifeTime {
                Value = 15
            });

            // Create the joint
            float3 pivotLocal  = float3.zero;
            var    joint       = PhysicsJoint.CreateBallAndSocket(pivotLocal, pivotWorld);
            var    jointEntity = CreateJoint(joint, body, Entity.Null);

            // add timeout on joint entity after 30 frames.
            manager.AddComponentData(jointEntity, new LifeTime {
                Value = 30
            });
        }

        // Add two static bodies constrained together
        // The joint is invalid immediately
        {
            // Create a body
            Entity bodyA = CreateStaticBody(new float3(0, 0.0f, 0), quaternion.identity, collider);
            Entity bodyB = CreateStaticBody(new float3(0, 1.0f, 0), quaternion.identity, collider);

            // Create the joint
            float3 pivotLocal  = float3.zero;
            var    joint       = PhysicsJoint.CreateBallAndSocket(pivotLocal, pivotLocal);
            var    jointEntity = CreateJoint(joint, bodyA, bodyB);

            // add timeout on joint entity after 15 frames.
            manager.AddComponentData(jointEntity, new LifeTime {
                Value = 15
            });
        }
    }
Exemple #14
0
        public static void Create2D(EntityManager entityManager, Entity entity, RigidTransform xform)
        {
            entityManager.AddComponent <PhysicsJointEntityTag>(entity);

            PhysicsJoint componentData = CreatePhysicsJoint2D(entity, xform);
            Entity       jointEntity   = entityManager.CreateEntity();

            entityManager.AddComponentData(jointEntity, componentData);
        }
Exemple #15
0
        public static void Create2D(EntityCommandBuffer.Concurrent ecb, int jobIndex, Entity entity, RigidTransform xform)
        {
            ecb.AddComponent <PhysicsJointEntityTag>(jobIndex, entity);

            PhysicsJoint componentData = CreatePhysicsJoint2D(entity, xform);
            Entity       jointEntity   = ecb.CreateEntity(jobIndex);

            ecb.AddComponent(jobIndex, jointEntity, componentData);
        }
Exemple #16
0
 public override void Create(EntityManager entityManager, GameObjectConversionSystem conversionSystem)
 {
     UpdateAuto();
     conversionSystem.World.GetOrCreateSystem <EndJointConversionSystem>().CreateJointEntity(
         this,
         GetConstrainedBodyPair(conversionSystem),
         PhysicsJoint.CreateBallAndSocket(PositionLocal, PositionInConnectedEntity)
         );
 }
Exemple #17
0
        public static void Create2D(EntityCommandBuffer ecb, Entity entity, RigidTransform xform)
        {
            ecb.AddComponent <PhysicsJointEntityTag>(entity);

            PhysicsJoint componentData = CreatePhysicsJoint2D(entity, xform);
            Entity       jointEntity   = ecb.CreateEntity();

            ecb.AddComponent(jointEntity, componentData);
        }
 public JointDesc(string name, simengine.VisualEntity jointEntity, PhysicsJoint joint)
 {
     Name        = name;
     JointEntity = jointEntity;
     Swing1Angle = 0;
     Swing2Angle = 0;
     TwistAngle  = 0;
     X           = Y = Z = 0;
     Joint       = joint;
 }
Exemple #19
0
    protected override unsafe void Start()
    {
        init();

        BlobAssetReference <Collider> collider = BoxCollider.Create(new BoxGeometry
        {
            Center      = float3.zero,
            Orientation = quaternion.identity,
            Size        = new float3(0.2f, 0.2f, 0.2f),
            BevelRadius = 0.0f
        });

        // Make some 1d angular limit joints
        const int   size  = 6;
        const float speed = 1.0f;
        int         iDbg  = 0;
        int         jDbg  = 3;

        for (int i = 0; i < size; i++)
        {
            quaternion q1 = quaternion.AxisAngle(new float3(1, 0, 0), (float)math.PI * 2.0f * i / size);
            for (int j = 0; j < size; j++)
            {
                if (iDbg >= 0 && jDbg >= 0 && (i != iDbg || j != jDbg))
                {
                    continue;
                }

                // Choose the limited axis
                quaternion q2 = quaternion.AxisAngle(math.mul(q1, new float3(0, 1, 0)),
                                                     (float)math.PI * ((float)j / size));

                // Create a body with some angular velocity about the axis
                float3 pos  = new float3(i - (size - 1) / 2.0f, 0, j - (size - 1) / 2.0f);
                Entity body = CreateDynamicBody(pos, quaternion.identity, collider, float3.zero,
                                                math.mul(q2, new float3(speed, 0, 0)), 1.0f);

                // Create a 1D angular limit about the axis
                float3x3 rotationB = float3x3.identity;
                float3x3 rotationA = math.mul(new float3x3(q2), rotationB);
                var      jointData = new PhysicsJoint
                {
                    BodyAFromJoint = new RigidTransform(rotationA, new float3(0, 0, 0)),
                    BodyBFromJoint = new RigidTransform(rotationB, pos)
                };
                jointData.SetConstraints(new FixedList128 <Constraint>
                {
                    Length = 1,
                    [0]    = Constraint.Twist(0, new FloatRange(-math.PI / 4f, math.PI / 4f))
                });

                CreateJoint(jointData, body, Entity.Null);
            }
        }
    }
Exemple #20
0
    public override void CreateScene(InvalidPhysicsJointExcludeDemoScene sceneSettings)
    {
        float colliderSize = 0.25f;

        BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.BoxCollider.Create(new BoxGeometry
        {
            Center      = float3.zero,
            Orientation = quaternion.identity,
            Size        = new float3(colliderSize),
            BevelRadius = 0.0f
        });

        CreatedColliders.Add(collider);

        float timeToSwap = sceneSettings.TimeToSwap;

        var bodyAPos = new float3(2f, 5.0f, 2);
        var bodyBPos = new float3(2f, 6.0f, 2);

        // Add constrained dynamic/dynamic body pair that will have their bodies excluded
        bool buildThisSection = true;

        if (buildThisSection)
        {
            bodyAPos += new float3(1, 0, 0);
            bodyBPos += new float3(1, 0, 0);

            // Create a body
            Entity bodyA = CreateDynamicBody(bodyAPos, quaternion.identity, collider, float3.zero, float3.zero, 1.0f);
            Entity bodyB = CreateDynamicBody(bodyBPos, quaternion.identity, collider, float3.zero, float3.zero, 1.0f);

            for (int i = 0; i < 2; i++)
            {
                // Create the joint
                var joint       = PhysicsJoint.CreateBallAndSocket(new float3(0, colliderSize, 0), new float3(0, -colliderSize, 0));
                var jointEntity = CreateJoint(joint, bodyA, bodyB);

                var pair = EntityManager.GetComponentData <PhysicsConstrainedBodyPair>(jointEntity);
                pair.EnableCollision = 1;
                EntityManager.SetComponentData(jointEntity, pair);
            }

            // add exclude components.
            EntityManager.AddComponentData(bodyA, new InvalidPhysicsJointExcludeBodies {
            });
            EntityManager.AddComponentData(bodyA, new InvalidPhysicsJointExcludeTimerEvent {
                TimeLimit = timeToSwap, Timer = timeToSwap
            });
            EntityManager.AddComponentData(bodyB, new InvalidPhysicsJointExcludeBodies {
            });
            EntityManager.AddComponentData(bodyB, new InvalidPhysicsJointExcludeTimerEvent {
                TimeLimit = timeToSwap, Timer = timeToSwap
            });
        }
    }
            public float Speed;  // Rate of moving toward the target position
            public JointDesc(string name, float min, float max, VisualEntity parentEntity, bool useNormal)
            {
                Name = name; Min = min; Max = max;
                _parentEntity = parentEntity;
                _useNormal = useNormal;

                Joint = null;
                Joint2 = null;
                Current = Target = 0;
                Speed = 30;
            }
 public override void Create(EntityManager entityManager, GameObjectConversionSystem conversionSystem)
 {
     UpdateAuto();
     conversionSystem.World.GetOrCreateSystem <EndJointConversionSystem>().CreateJointEntity(
         this,
         GetConstrainedBodyPair(conversionSystem),
         PhysicsJoint.CreateFixed(
             new RigidTransform(OrientationLocal, PositionLocal),
             new RigidTransform(OrientationInConnectedEntity, PositionInConnectedEntity)
             )
         );
 }
Exemple #23
0
 public override void Create(EntityManager entityManager, GameObjectConversionSystem conversionSystem)
 {
     UpdateAuto();
     conversionSystem.World.GetOrCreateSystem <EndJointConversionSystem>().CreateJointEntity(
         this,
         GetConstrainedBodyPair(conversionSystem),
         PhysicsJoint.CreateLimitedDistance(
             PositionLocal,
             PositionInConnectedEntity,
             new FloatRange(MinDistance, MaxDistance)
             )
         );
 }
Exemple #24
0
        protected override void RemoveJoint(PhysicsJoint joint)
        {
            var jitterJoint = joint as JitterJoint;

            if (jitterJoint.Constraint != null)
            {
                jitterWorld.RemoveConstraint(jitterJoint.Constraint);
            }
            else
            {
                jitterJoint.Joint.Deactivate();
            }
        }
    protected override void Start()
    {
        base.Start();

        // Enable the joint viewer
        SetDebugDisplay(new Unity.Physics.Authoring.PhysicsDebugDisplayData
        {
            DrawJoints = 1
        });

        BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.BoxCollider.Create(new BoxGeometry
        {
            Center      = float3.zero,
            Orientation = quaternion.identity,
            Size        = new float3(0.2f, 1.0f, 0.2f),
            BevelRadius = 0.0f
        });

        // Make some ragdoll joints
        for (int i = 0; i < 10; i++)
        {
            // Create a body
            Entity body = CreateDynamicBody(
                new float3((i - 4.5f) * 1.0f, 0, 0), quaternion.identity, collider, float3.zero, float3.zero, 1.0f);

            // Create the ragdoll joint
            float3 pivotLocal         = new float3(0, 0.5f, 0);
            float3 pivotInWorld       = math.transform(GetBodyTransform(body), pivotLocal);
            float3 axisLocal          = new float3(0, 1, 0);
            float3 perpendicularLocal = new float3(0, 0, 1);

            quaternion worldFromLocal     = Quaternion.AngleAxis((i - 4.5f) * 20.0f, new float3(0, 0, 1));
            float3     axisWorld          = math.mul(worldFromLocal, axisLocal);
            float3     perpendicularWorld = math.mul(worldFromLocal, perpendicularLocal);

            float maxConeAngle       = (float)math.PI / 4.0f;
            var   perpendicularAngle = new FloatRange(-math.PI / 2f, math.PI / 2f);
            var   twistAngle         = new FloatRange(-math.PI / 8f, math.PI / 8f);

            var localFrame = new BodyFrame {
                Axis = axisLocal, PerpendicularAxis = perpendicularLocal, Position = pivotLocal
            };
            var worldFrame = new BodyFrame {
                Axis = axisWorld, PerpendicularAxis = perpendicularWorld, Position = pivotInWorld
            };
            PhysicsJoint.CreateRagdoll(localFrame, worldFrame, maxConeAngle, perpendicularAngle, twistAngle, out var ragdoll0, out var ragdoll1);
            CreateJoint(ragdoll0, body, Entity.Null);
            CreateJoint(ragdoll1, body, Entity.Null);
        }
    }
Exemple #26
0
        private static PhysicsJoint CreatePhysicsJoint2D(Entity entity, RigidTransform xform)
        {
            BlobAssetReference <JointData> joint = CreateLimitDOFJoint(xform, new bool3(false, false, true), new bool3(true, true, false));

            var componentData = new PhysicsJoint
            {
                JointData       = joint,
                EntityA         = entity,
                EntityB         = Entity.Null,
                EnableCollision = 0,
            };

            return(componentData);
        }
Exemple #27
0
    protected Entity CreateJoint(PhysicsJoint joint, Entity entityA, Entity entityB, bool enableCollision = false)
    {
        var entityManager = DefaultWorld.EntityManager;

        ComponentType[] componentTypes =
        {
            typeof(PhysicsConstrainedBodyPair),
            typeof(PhysicsJoint)
        };
        Entity jointEntity = entityManager.CreateEntity(componentTypes);

        entityManager.SetComponentData(jointEntity, new PhysicsConstrainedBodyPair(entityA, entityB, enableCollision));
        entityManager.SetComponentData(jointEntity, joint);

        return(jointEntity);
    }
 public override void Create(EntityManager entityManager, GameObjectConversionSystem conversionSystem)
 {
     UpdateAuto();
     conversionSystem.World.GetOrCreateSystem <EndJointConversionSystem>().CreateJointEntity(
         this,
         GetConstrainedBodyPair(conversionSystem),
         PhysicsJoint.CreateHinge(
             new BodyFrame {
         Axis = HingeAxisLocal, Position = PositionLocal
     },
             new BodyFrame {
         Axis = HingeAxisInConnectedEntity, Position = PositionInConnectedEntity
     }
             )
         );
 }
Exemple #29
0
        // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
        // alert the user of errors by using the debug channel in the same way that scripts alert
        // the user of compile errors.

        // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
        // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
        // from within the OdePhysicsScene.
        public void jointErrorMessage(PhysicsJoint joint, string message)
        {
            if (joint != null)
            {
                if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
                {
                    return;
                }

                SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
                if (jointProxyObject != null)
                {
                    IChatModule chatModule = m_scene.RequestModuleInterface <IChatModule>();
                    if (chatModule != null)
                    {
                        chatModule.SimChat("[NINJA]: " + message,
                                           ChatTypeEnum.DebugChannel,
                                           2147483647,
                                           jointProxyObject.AbsolutePosition,
                                           jointProxyObject.Name,
                                           jointProxyObject.UUID,
                                           false, m_scene);
                    }

                    joint.ErrorMessageCount++;

                    if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
                    {
                        if (chatModule != null)
                        {
                            chatModule.SimChat("[NINJA]: Too many messages for this joint, suppressing further messages.",
                                               ChatTypeEnum.DebugChannel,
                                               2147483647,
                                               jointProxyObject.AbsolutePosition,
                                               jointProxyObject.Name,
                                               jointProxyObject.UUID,
                                               false, m_scene);
                        }
                    }
                }
                else
                {
                    // couldn't find the joint proxy object; the error message is silently suppressed
                }
            }
        }
 public override void Create(EntityManager entityManager, GameObjectConversionSystem conversionSystem)
 {
     UpdateAuto();
     Math.CalculatePerpendicularNormalized(HingeAxisLocal, out var perpendicularLocal, out _);
     Math.CalculatePerpendicularNormalized(HingeAxisInConnectedEntity, out var perpendicularConnected, out _);
     conversionSystem.World.GetOrCreateSystem <EndJointConversionSystem>().CreateJointEntity(
         this,
         GetConstrainedBodyPair(conversionSystem),
         PhysicsJoint.CreateHinge(
             new BodyFrame {
         Axis = HingeAxisLocal, Position = PositionLocal, PerpendicularAxis = perpendicularLocal
     },
             new BodyFrame {
         Axis = HingeAxisInConnectedEntity, Position = PositionInConnectedEntity, PerpendicularAxis = perpendicularConnected
     }
             )
         );
 }
    public Entity CreateJoint(PhysicsJoint joint, Entity entityA, Entity entityB, bool enableCollision = false)
    {
        var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

        ComponentType[] componentTypes =
        {
            typeof(PhysicsConstrainedBodyPair),
            typeof(PhysicsJoint)
        };
        Entity jointEntity = entityManager.CreateEntity(componentTypes);

        entityManager.SetComponentData(jointEntity, new PhysicsConstrainedBodyPair(entityA, entityB, enableCollision));
        entityManager.SetComponentData(jointEntity, joint);

        EntityManager.AddSharedComponentData(jointEntity, new PhysicsWorldIndex());

        return(jointEntity);
    }
            public bool Update(double prevTime, float epsilon)
            {
                if (Joint == null)
                    Joint = (PhysicsJoint)_parentEntity.ParentJoint;

                if (!NeedToMove(epsilon))
                    return false;


                UpdateCurrent(prevTime);

                Vector3 axis = _useNormal ? Joint.State.Connectors[0].JointNormal : Joint.State.Connectors[0].JointAxis;
                Joint.SetAngularDriveOrientation(
                    Quaternion.FromAxisAngle(axis.X, axis.Y, axis.Z, Conversions.DegreesToRadians(Current)));

                return true;
            }
Exemple #33
0
 protected virtual void DoJointErrorMessage(PhysicsJoint joint, string message)
 {
     // We need this to allow subclasses (but not other classes) to invoke the event; C# does
     // not allow subclasses to invoke the parent class event.
     if (OnJointErrorMessage != null)
     {
         OnJointErrorMessage(joint, message);
     }
 }
Exemple #34
0
 public virtual Vector3 GetJointAxis(PhysicsJoint joint)
 { return Vector3.Zero; }
Exemple #35
0
 protected virtual void DoJointDeactivated(PhysicsJoint joint)
 {
     // We need this to allow subclasses (but not other classes) to invoke the event; C# does
     // not allow subclasses to invoke the parent class event.
     if (OnJointDeactivated != null)
     {
         OnJointDeactivated(joint);
     }
 }
Exemple #36
0
		protected override void RemoveJoint(PhysicsJoint joint)
		{
			var jitterJoint = joint as JitterJoint;
			if (jitterJoint.Constraint != null)
				jitterWorld.RemoveConstraint(jitterJoint.Constraint);
			else
				jitterJoint.Joint.Deactivate();
		}