private void INTERNAL_get_highTwistLimit(out SoftJointLimit value){}
		private void INTERNAL_get_swing2Limit(out SoftJointLimit value){}
Esempio n. 3
0
 private void AngularZLimit(Action action)
 {
     Enum <ConfigurableJoint>(j => { _softJointLimit = j.angularZLimit; action.Invoke(); j.angularZLimit = _softJointLimit; });
 }
Esempio n. 4
0
    private void BuildRope()
    {
        tubeRenderer = new GameObject("TubeRenderer_" + gameObject.name);
        // присоединяем к GameObject класс, получаем ссылку на объект этого класса
        line = tubeRenderer.AddComponent <TubeRenderer2>();  // теперь line - экземпляр TubeRenderer2
        line.useMeshCollision = useMeshCollision;
        // Find the amount of segments based on the distance and resolution
        // Example: [resolution of 1.0 = 1 joint per unit of distance]
        segments = Mathf.FloorToInt(Vector3.Distance(transform.position, target.position) * resolution);

        if (material != null)
        {
            material.SetTextureScale("_MainTex", new Vector2(1, segments + 2));
            if (material.GetTexture("_BumpMap"))
            {
                material.SetTextureScale("_BumpMap", new Vector2(1, segments + 2));
            }
        }
        line.vertices            = new TubeVertex[segments];
        line.crossSegments       = radialSegments;
        line.material            = material;
        segmentPos               = new Vector3[segments];
        joints                   = new GameObject[segments];
        segmentPos[0]            = transform.position;
        segmentPos[segments - 1] = target.position;

        // Find the distance between each segment
        int     segs       = segments - 1;
        Vector3 seperation = ((target.position - transform.position) / segs);

        for (int s = 0; s < segments; s++)
        {
            // Find the each segments position using the slope from above
            Vector3 vector = (seperation * s) + transform.position;
            segmentPos[s] = vector;
            //Add Physics to the segments
            AddJointPhysics(s);
        }
        // Attach the joints to the target object and parent it to this object
        CharacterJoint end = target.gameObject.AddComponent <CharacterJoint> ();

        end.connectedBody = joints[joints.Length - 1].transform.GetComponent <Rigidbody> ();
        end.swingAxis     = swingAxis;
        SoftJointLimit limit1 = end.lowTwistLimit;

        limit1.limit      = lowTwistLimit;
        end.lowTwistLimit = limit1;
        SoftJointLimit limit2 = end.highTwistLimit;

        limit2.limit       = highTwistLimit;
        end.highTwistLimit = limit2;
        SoftJointLimit limit3 = end.swing1Limit;

        limit3.limit    = swing1Limit;
        end.swing1Limit = limit3;

        target.parent = transform;
        if (endRestrained)
        {
            end.GetComponent <Rigidbody> ().isKinematic = true;
        }

        // FEDOR *****************
        end.GetComponent <Rigidbody>().useGravity = gameObject.GetComponent <Rigidbody>().useGravity;
        // ***********************

        if (startRestrained)
        {
            transform.GetComponent <Rigidbody> ().isKinematic = true;
        }
        // Rope = true, The rope now exists in the scene!
        rope = true;
    }
        private static void SetMotionAngularLock(Constraint joint, ConfigurableJoint conf)
        {
            SoftJointLimit jlim;

            if (Math.Abs(joint.PositionLowLimit.x) < Tools.MmdMathConstEps && Math.Abs(joint.PositionHiLimit.x) < Tools.MmdMathConstEps)
            {
                conf.xMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.xMotion = ConfigurableJointMotion.Limited;
            }

            if (Math.Abs(joint.PositionLowLimit.y) < Tools.MmdMathConstEps && Math.Abs(joint.PositionHiLimit.y) < Tools.MmdMathConstEps)
            {
                conf.yMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.yMotion = ConfigurableJointMotion.Limited;
            }

            if (Math.Abs(joint.PositionLowLimit.z) < Tools.MmdMathConstEps && Math.Abs(joint.PositionHiLimit.z) < Tools.MmdMathConstEps)
            {
                conf.zMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.zMotion = ConfigurableJointMotion.Limited;
            }

            if (Math.Abs(joint.RotationLowLimit.x) < Tools.MmdMathConstEps && Math.Abs(joint.RotationHiLimit.x) < Tools.MmdMathConstEps)
            {
                conf.angularXMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.angularXMotion = ConfigurableJointMotion.Limited;
                var hlim  = Mathf.Max(-joint.RotationLowLimit.x, -joint.RotationHiLimit.x);
                var llim  = Mathf.Min(-joint.RotationLowLimit.x, -joint.RotationHiLimit.x);
                var jhlim = new SoftJointLimit {
                    limit = Mathf.Clamp(hlim * Mathf.Rad2Deg, -180.0f, 180.0f)
                };
                conf.highAngularXLimit = jhlim;

                var jllim = new SoftJointLimit {
                    limit = Mathf.Clamp(llim * Mathf.Rad2Deg, -180.0f, 180.0f)
                };
                conf.lowAngularXLimit = jllim;
            }

            if (Math.Abs(joint.RotationLowLimit.y) < Tools.MmdMathConstEps && Math.Abs(joint.RotationHiLimit.y) < Tools.MmdMathConstEps)
            {
                conf.angularYMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.angularYMotion = ConfigurableJointMotion.Limited;
                conf.angularYMotion = ConfigurableJointMotion.Limited;
                var lim = Mathf.Min(Mathf.Abs(joint.RotationLowLimit.y), Mathf.Abs(joint.RotationHiLimit.y));
                jlim = new SoftJointLimit {
                    limit = lim * Mathf.Clamp(Mathf.Rad2Deg, 0.0f, 180.0f)
                };
                conf.angularYLimit = jlim;
            }

            if (Math.Abs(joint.RotationLowLimit.z) < Tools.MmdMathConstEps && Math.Abs(joint.RotationHiLimit.z) < Tools.MmdMathConstEps)
            {
                conf.angularZMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.angularZMotion = ConfigurableJointMotion.Limited;
                var lim = Mathf.Min(Mathf.Abs(-joint.RotationLowLimit.z), Mathf.Abs(-joint.RotationHiLimit.z));
                jlim = new SoftJointLimit {
                    limit = Mathf.Clamp(lim * Mathf.Rad2Deg, 0.0f, 180.0f)
                };
                conf.angularZLimit = jlim;
            }
        }
        private void UpdatePartJoint(Part p)
        {
            if (!KJRJointUtils.JointAdjustmentValid(p) || p.rb == null || p.attachJoint == null)
            {
                return;
            }

            if (p.attachMethod == AttachNodeMethod.LOCKED_JOINT)
            {
                if (KJRJointUtils.debug)
                {
                    Debug.Log("KJR: Already processed part before: " + p.partInfo.name + " (" + p.flightID + ") -> " +
                              p.parent.partInfo.name + " (" + p.parent.flightID + ")");
                }

                return;
            }
            List <ConfigurableJoint> jointList;

            if (p is StrutConnector)
            {
                StrutConnector s = p as StrutConnector;

                if (s.jointTarget == null || s.jointRoot == null)
                {
                    return;
                }

                jointList = KJRJointUtils.GetJointListFromAttachJoint(s.strutJoint);

                if (jointList != null)
                {
                    for (int i = 0; i < jointList.Count; i++)
                    {
                        ConfigurableJoint j = jointList[i];

                        if (j == null)
                        {
                            continue;
                        }

                        JointDrive strutDrive = j.angularXDrive;
                        strutDrive.positionSpring = KJRJointUtils.decouplerAndClampJointStrength;
                        strutDrive.maximumForce   = KJRJointUtils.decouplerAndClampJointStrength;
                        j.xDrive = j.yDrive = j.zDrive = j.angularXDrive = j.angularYZDrive = strutDrive;

                        j.xMotion        = j.yMotion = j.zMotion = ConfigurableJointMotion.Locked;
                        j.angularXMotion = j.angularYMotion = j.angularZMotion = ConfigurableJointMotion.Locked;

                        //float scalingFactor = (s.jointTarget.mass + s.jointTarget.GetResourceMass() + s.jointRoot.mass + s.jointRoot.GetResourceMass()) * 0.01f;

                        j.breakForce  = KJRJointUtils.decouplerAndClampJointStrength;
                        j.breakTorque = KJRJointUtils.decouplerAndClampJointStrength;
                    }

                    p.attachMethod = AttachNodeMethod.LOCKED_JOINT;
                }
            }
            if (p.Modules.Contains <CModuleStrut>())
            {
                CModuleStrut s = p.Modules.GetModule <CModuleStrut>();

                if (!(s.jointTarget == null || s.jointRoot == null))
                {
                    jointList = KJRJointUtils.GetJointListFromAttachJoint(s.strutJoint);

                    if (jointList != null)
                    {
                        for (int i = 0; i < jointList.Count; i++)
                        {
                            ConfigurableJoint j = jointList[i];

                            if (j == null)
                            {
                                continue;
                            }

                            JointDrive strutDrive = j.angularXDrive;
                            strutDrive.positionSpring = KJRJointUtils.decouplerAndClampJointStrength;
                            strutDrive.maximumForce   = KJRJointUtils.decouplerAndClampJointStrength;
                            j.xDrive = j.yDrive = j.zDrive = j.angularXDrive = j.angularYZDrive = strutDrive;

                            j.xMotion        = j.yMotion = j.zMotion = ConfigurableJointMotion.Locked;
                            j.angularXMotion = j.angularYMotion = j.angularZMotion = ConfigurableJointMotion.Locked;

                            //float scalingFactor = (s.jointTarget.mass + s.jointTarget.GetResourceMass() + s.jointRoot.mass + s.jointRoot.GetResourceMass()) * 0.01f;

                            j.breakForce  = KJRJointUtils.decouplerAndClampJointStrength;
                            j.breakTorque = KJRJointUtils.decouplerAndClampJointStrength;
                        }

                        p.attachMethod = AttachNodeMethod.LOCKED_JOINT;
                    }
                }
            }


            jointList = KJRJointUtils.GetJointListFromAttachJoint(p.attachJoint);
            if (jointList == null)
            {
                return;
            }

            StringBuilder debugString = new StringBuilder();

            bool addAdditionalJointToParent = KJRJointUtils.multiPartAttachNodeReinforcement;

            //addAdditionalJointToParent &= !(p.Modules.Contains("LaunchClamp") || (p.parent.Modules.Contains("ModuleDecouple") || p.parent.Modules.Contains("ModuleAnchoredDecoupler")));
            addAdditionalJointToParent &= !(p is StrutConnector || p.Modules.Contains <CModuleStrut>());

            float partMass = p.mass + p.GetResourceMass();

            for (int i = 0; i < jointList.Count; i++)
            {
                ConfigurableJoint j = jointList[i];
                if (j == null)
                {
                    continue;
                }

                String    jointType     = j.GetType().Name;
                Rigidbody connectedBody = j.connectedBody;

                Part  connectedPart = connectedBody.GetComponent <Part>() ?? p.parent;
                float parentMass    = connectedPart.mass + connectedPart.GetResourceMass();

                if (partMass < KJRJointUtils.massForAdjustment || parentMass < KJRJointUtils.massForAdjustment)
                {
                    if (KJRJointUtils.debug)
                    {
                        Debug.Log("KJR: Part mass too low, skipping: " + p.partInfo.name + " (" + p.flightID + ")");
                    }

                    continue;
                }

                // Check attachment nodes for better orientation data
                AttachNode attach   = p.findAttachNodeByPart(p.parent);
                AttachNode p_attach = p.parent.findAttachNodeByPart(p);
                AttachNode node     = attach ?? p_attach;

                if (node == null)
                {
                    // Check if it's a pair of coupled docking ports
                    var dock1 = p.Modules.GetModule <ModuleDockingNode>();
                    var dock2 = p.parent.Modules.GetModule <ModuleDockingNode>();

                    //Debug.Log(dock1 + " " + (dock1 ? ""+dock1.dockedPartUId : "?") + " " + dock2 + " " + (dock2 ? ""+dock2.dockedPartUId : "?"));

                    if (dock1 && dock2 && (dock1.dockedPartUId == p.parent.flightID || dock2.dockedPartUId == p.flightID))
                    {
                        attach   = p.findAttachNode(dock1.referenceAttachNode);
                        p_attach = p.parent.findAttachNode(dock2.referenceAttachNode);
                        node     = attach ?? p_attach;
                    }
                }

                // If still no node and apparently surface attached, use the normal one if it's there
                if (node == null && p.attachMode == AttachModes.SRF_ATTACH)
                {
                    node = attach = p.srfAttachNode;
                }

                if (KJRJointUtils.debug)
                {
                    debugString.AppendLine("Original joint from " + p.partInfo.title + " to " + p.parent.partInfo.title);
                    debugString.AppendLine("  " + p.partInfo.name + " (" + p.flightID + ") -> " + p.parent.partInfo.name + " (" + p.parent.flightID + ")");
                    debugString.AppendLine("");
                    debugString.AppendLine(p.partInfo.title + " Inertia Tensor: " + p.rb.inertiaTensor + " " + p.parent.partInfo.name + " Inertia Tensor: " + connectedBody.inertiaTensor);
                    debugString.AppendLine("");


                    debugString.AppendLine("Std. Joint Parameters");
                    debugString.AppendLine("Connected Body: " + p.attachJoint.Joint.connectedBody);
                    debugString.AppendLine("Attach mode: " + p.attachMode + " (was " + jointType + ")");
                    if (attach != null)
                    {
                        debugString.AppendLine("Attach node: " + attach.id + " - " + attach.nodeType + " " + attach.size);
                    }
                    if (p_attach != null)
                    {
                        debugString.AppendLine("Parent node: " + p_attach.id + " - " + p_attach.nodeType + " " + p_attach.size);
                    }
                    debugString.AppendLine("Anchor: " + p.attachJoint.Joint.anchor);
                    debugString.AppendLine("Axis: " + p.attachJoint.Joint.axis);
                    debugString.AppendLine("Sec Axis: " + p.attachJoint.Joint.secondaryAxis);
                    debugString.AppendLine("Break Force: " + p.attachJoint.Joint.breakForce);
                    debugString.AppendLine("Break Torque: " + p.attachJoint.Joint.breakTorque);
                    debugString.AppendLine("");

                    debugString.AppendLine("Joint Motion Locked: " + Convert.ToString(p.attachJoint.Joint.xMotion == ConfigurableJointMotion.Locked));

                    debugString.AppendLine("X Drive");
                    debugString.AppendLine("Position Spring: " + p.attachJoint.Joint.xDrive.positionSpring);
                    debugString.AppendLine("Position Damper: " + p.attachJoint.Joint.xDrive.positionDamper);
                    debugString.AppendLine("Max Force: " + p.attachJoint.Joint.xDrive.maximumForce);
                    debugString.AppendLine("Mode: " + p.attachJoint.Joint.xDrive.mode);
                    debugString.AppendLine("");

                    debugString.AppendLine("Y Drive");
                    debugString.AppendLine("Position Spring: " + p.attachJoint.Joint.yDrive.positionSpring);
                    debugString.AppendLine("Position Damper: " + p.attachJoint.Joint.yDrive.positionDamper);
                    debugString.AppendLine("Max Force: " + p.attachJoint.Joint.yDrive.maximumForce);
                    debugString.AppendLine("Mode: " + p.attachJoint.Joint.yDrive.mode);
                    debugString.AppendLine("");

                    debugString.AppendLine("Z Drive");
                    debugString.AppendLine("Position Spring: " + p.attachJoint.Joint.zDrive.positionSpring);
                    debugString.AppendLine("Position Damper: " + p.attachJoint.Joint.zDrive.positionDamper);
                    debugString.AppendLine("Max Force: " + p.attachJoint.Joint.zDrive.maximumForce);
                    debugString.AppendLine("Mode: " + p.attachJoint.Joint.zDrive.mode);
                    debugString.AppendLine("");

                    debugString.AppendLine("Angular X Drive");
                    debugString.AppendLine("Position Spring: " + p.attachJoint.Joint.angularXDrive.positionSpring);
                    debugString.AppendLine("Position Damper: " + p.attachJoint.Joint.angularXDrive.positionDamper);
                    debugString.AppendLine("Max Force: " + p.attachJoint.Joint.angularXDrive.maximumForce);
                    debugString.AppendLine("Mode: " + p.attachJoint.Joint.angularXDrive.mode);
                    debugString.AppendLine("");

                    debugString.AppendLine("Angular YZ Drive");
                    debugString.AppendLine("Position Spring: " + p.attachJoint.Joint.angularYZDrive.positionSpring);
                    debugString.AppendLine("Position Damper: " + p.attachJoint.Joint.angularYZDrive.positionDamper);
                    debugString.AppendLine("Max Force: " + p.attachJoint.Joint.angularYZDrive.maximumForce);
                    debugString.AppendLine("Mode: " + p.attachJoint.Joint.angularYZDrive.mode);
                    debugString.AppendLine("");


                    //Debug.Log(debugString.ToString());
                }


                float   breakForce      = Math.Min(p.breakingForce, connectedPart.breakingForce) * KJRJointUtils.breakForceMultiplier;
                float   breakTorque     = Math.Min(p.breakingTorque, connectedPart.breakingTorque) * KJRJointUtils.breakTorqueMultiplier;
                Vector3 anchor          = j.anchor;
                Vector3 connectedAnchor = j.connectedAnchor;
                Vector3 axis            = j.axis;

                float radius          = 0;
                float area            = 0;
                float momentOfInertia = 0;

                if (node != null)
                {
                    // Part that owns the node. For surface attachment,
                    // this can only be parent if docking flips hierarchy.
                    Part main = (node == attach) ? p : p.parent;

                    // Orientation and position of the node in owner's local coords
                    Vector3 ndir = node.orientation.normalized;
                    Vector3 npos = node.position + node.offset;

                    // And in the current part's local coords
                    Vector3 dir = axis = p.transform.InverseTransformDirection(main.transform.TransformDirection(ndir));

                    if (node.nodeType == AttachNode.NodeType.Surface)
                    {
                        // Guessed main axis; for parts with stack nodes should be the axis of the stack
                        Vector3 up = KJRJointUtils.GuessUpVector(main).normalized;

                        // if guessed up direction is same as node direction, it's basically stack
                        // for instance, consider a radially-attached docking port
                        if (Mathf.Abs(Vector3.Dot(up, ndir)) > 0.9f)
                        {
                            radius = Mathf.Min(KJRJointUtils.CalculateRadius(main, ndir), KJRJointUtils.CalculateRadius(connectedPart, ndir));
                            if (radius <= 0.001)
                            {
                                radius = node.size * 1.25f;
                            }
                            area            = Mathf.PI * radius * radius;           //Area of cylinder
                            momentOfInertia = area * radius * radius / 4;           //Moment of Inertia of cylinder
                        }
                        else
                        {
                            // x along surface, y along ndir normal to surface, z along surface & main axis (up)
                            var size1 = KJRJointUtils.CalculateExtents(main, ndir, up);

                            var size2 = KJRJointUtils.CalculateExtents(connectedPart, ndir, up);

                            // use average of the sides, since we don't know which one is used for attaching
                            float width1 = (size1.x + size1.z) / 2;
                            float width2 = (size2.x + size2.z) / 2;
                            if (size1.y * width1 > size2.y * width2)
                            {
                                area   = size1.y * width1;
                                radius = Mathf.Max(size1.y, width1);
                            }
                            else
                            {
                                area   = size2.y * width2;
                                radius = Mathf.Max(size2.y, width2);
                            }

                            momentOfInertia = area * radius / 12;          //Moment of Inertia of a rectangle bending along the longer length
                        }
                    }
                    else
                    {
                        radius = Mathf.Min(KJRJointUtils.CalculateRadius(p, dir), KJRJointUtils.CalculateRadius(connectedPart, dir));
                        if (radius <= 0.001)
                        {
                            radius = node.size * 1.25f;
                        }
                        area            = Mathf.PI * radius * radius;           //Area of cylinder
                        momentOfInertia = area * radius * radius / 4;           //Moment of Inertia of cylinder
                    }
                }
                //Assume part is attached along its "up" cross section; use a cylinder to approximate properties
                else if (p.attachMode == AttachModes.STACK)
                {
                    radius = Mathf.Min(KJRJointUtils.CalculateRadius(p, Vector3.up), KJRJointUtils.CalculateRadius(connectedPart, Vector3.up));
                    if (radius <= 0.001)
                    {
                        radius = node.size * 1.25f;
                    }
                    area            = Mathf.PI * radius * radius;           //Area of cylinder
                    momentOfInertia = area * radius * radius / 4;           //Moment of Inertia of cylinder
                }
                else if (p.attachMode == AttachModes.SRF_ATTACH)
                {
                    // x,z sides, y along main axis
                    Vector3 up1   = KJRJointUtils.GuessUpVector(p);
                    var     size1 = KJRJointUtils.CalculateExtents(p, up1);

                    Vector3 up2   = KJRJointUtils.GuessUpVector(connectedPart);
                    var     size2 = KJRJointUtils.CalculateExtents(connectedPart, up2);

                    // use average of the sides, since we don't know which one is used for attaching
                    float width1 = (size1.x + size1.z) / 2;
                    float width2 = (size2.x + size2.z) / 2;
                    if (size1.y * width1 > size2.y * width2)
                    {
                        area   = size1.y * width1;
                        radius = Mathf.Max(size1.y, width1);
                    }
                    else
                    {
                        area   = size2.y * width2;
                        radius = Mathf.Max(size2.y, width2);
                    }
                    momentOfInertia = area * radius / 12;          //Moment of Inertia of a rectangle bending along the longer length
                }

                if (KJRJointUtils.useVolumeNotArea)                //If using volume, raise al stiffness-affecting parameters to the 1.5 power
                {
                    area            = Mathf.Pow(area, 1.5f);
                    momentOfInertia = Mathf.Pow(momentOfInertia, 1.5f);
                }


                breakForce  = Mathf.Max(KJRJointUtils.breakStrengthPerArea * area, breakForce);
                breakTorque = Mathf.Max(KJRJointUtils.breakTorquePerMOI * momentOfInertia, breakTorque);

                JointDrive angDrive = j.angularXDrive;
                angDrive.positionSpring = Mathf.Max(momentOfInertia * KJRJointUtils.angularDriveSpring, angDrive.positionSpring);
                angDrive.positionDamper = Mathf.Max(momentOfInertia * KJRJointUtils.angularDriveDamper * 0.1f, angDrive.positionDamper);
                angDrive.maximumForce   = breakTorque;

                /*float moi_avg = p.rb.inertiaTensor.magnitude;
                 *
                 * moi_avg += (p.transform.localToWorldMatrix.MultiplyPoint(p.CoMOffset) - p.parent.transform.position).sqrMagnitude * p.rb.mass;
                 *
                 * if (moi_avg * 2f / drive.positionDamper < 0.08f)
                 * {
                 *  drive.positionDamper = moi_avg / (0.04f);
                 *
                 *  drive.positionSpring = drive.positionDamper * drive.positionDamper / moi_avg;
                 * }*/
                j.angularXDrive = j.angularYZDrive = j.slerpDrive = angDrive;

                JointDrive linDrive = j.xDrive;
                linDrive.maximumForce = breakForce;
                j.xDrive = j.yDrive = j.zDrive = linDrive;

                SoftJointLimit lim = new SoftJointLimit();
                lim.limit      = 0;
                lim.bounciness = 0;

                SoftJointLimitSpring limSpring = new SoftJointLimitSpring();

                limSpring.spring = 0;
                limSpring.damper = 0;

                j.linearLimit       = j.angularYLimit = j.angularZLimit = j.lowAngularXLimit = j.highAngularXLimit = lim;
                j.linearLimitSpring = j.angularYZLimitSpring = j.angularXLimitSpring = limSpring;

                j.targetAngularVelocity = Vector3.zero;
                j.targetVelocity        = Vector3.zero;
                j.targetRotation        = Quaternion.identity;
                j.targetPosition        = Vector3.zero;

                j.breakForce  = breakForce;
                j.breakTorque = breakTorque;
                p.attachJoint.SetBreakingForces(j.breakForce, j.breakTorque);

                p.attachMethod = AttachNodeMethod.LOCKED_JOINT;

                if (addAdditionalJointToParent && p.parent.parent != null)
                {
                    addAdditionalJointToParent = false;
                    if (!KJRJointUtils.JointAdjustmentValid(p.parent) || !KJRJointUtils.JointAdjustmentValid(p.parent.parent))
                    {
                        continue;
                    }

                    /*if (ValidDecoupler(p) || ValidDecoupler(p.parent))
                     *  continue;*/
                    Part newConnectedPart = p.parent.parent;

                    bool massRatioBelowThreshold = false;
                    int  numPartsFurther         = 0;

                    float       partMaxMass          = KJRJointUtils.MaximumPossiblePartMass(p);
                    List <Part> partsCrossed         = new List <Part>();
                    List <Part> possiblePartsCrossed = new List <Part>();

                    partsCrossed.Add(p);
                    partsCrossed.Add(p.parent);
                    partsCrossed.Add(newConnectedPart);

                    Rigidbody connectedRb = newConnectedPart.rb;

                    do
                    {
                        float massRat1, massRat2;
                        massRat1 = partMaxMass / newConnectedPart.mass;
                        if (massRat1 < 1)
                        {
                            massRat1 = 1 / massRat1;
                        }

                        massRat2 = p.mass / KJRJointUtils.MaximumPossiblePartMass(newConnectedPart);
                        if (massRat2 < 1)
                        {
                            massRat2 = 1 / massRat2;
                        }

                        if (massRat1 > KJRJointUtils.stiffeningExtensionMassRatioThreshold || massRat2 > KJRJointUtils.stiffeningExtensionMassRatioThreshold)
                        {
                            if (newConnectedPart.parent != null)
                            {
                                if (!KJRJointUtils.JointAdjustmentValid(newConnectedPart.parent))
                                {
                                    break;
                                }

                                newConnectedPart = newConnectedPart.parent;
                                if (newConnectedPart.rb == null)
                                {
                                    possiblePartsCrossed.Add(newConnectedPart);
                                }
                                else
                                {
                                    connectedRb = newConnectedPart.rb;
                                    partsCrossed.AddRange(possiblePartsCrossed);
                                    partsCrossed.Add(newConnectedPart);
                                    possiblePartsCrossed.Clear();
                                }
                            }
                            else
                            {
                                break;
                            }
                            numPartsFurther++;
                        }
                        else
                        {
                            massRatioBelowThreshold = true;
                        }
                    } while (!massRatioBelowThreshold);// && numPartsFurther < 5);

                    if (connectedRb != null && !multiJointManager.CheckMultiJointBetweenParts(p, newConnectedPart))
                    {
                        ConfigurableJoint newJoint = p.gameObject.AddComponent <ConfigurableJoint>();

                        newJoint.connectedBody   = connectedRb;
                        newJoint.axis            = Vector3.right;
                        newJoint.secondaryAxis   = Vector3.forward;
                        newJoint.anchor          = Vector3.zero;
                        newJoint.connectedAnchor = p.transform.worldToLocalMatrix.MultiplyPoint(newConnectedPart.transform.position);

                        //if(massRatioBelowThreshold)
                        //{

                        newJoint.angularXDrive = newJoint.angularYZDrive = newJoint.slerpDrive = j.angularXDrive;

                        newJoint.xDrive = j.xDrive;
                        newJoint.yDrive = j.yDrive;
                        newJoint.zDrive = j.zDrive;

                        newJoint.linearLimit = newJoint.angularYLimit = newJoint.angularZLimit = newJoint.lowAngularXLimit = newJoint.highAngularXLimit = lim;

                        /*newJoint.targetAngularVelocity = Vector3.zero;
                         * newJoint.targetVelocity = Vector3.zero;
                         * newJoint.targetRotation = Quaternion.identity;
                         * newJoint.targetPosition = Vector3.zero;*/
                        /*}
                         * else
                         * {
                         *  newJoint.xMotion = newJoint.yMotion = newJoint.zMotion = ConfigurableJointMotion.Locked;
                         *  newJoint.angularXMotion = newJoint.angularYMotion = newJoint.angularZMotion = ConfigurableJointMotion.Locked;
                         * }*/

                        newJoint.breakForce  = breakForce;
                        newJoint.breakTorque = breakTorque;

                        //jointList.Add(newJoint);
                        for (int k = 0; k < partsCrossed.Count; k++)
                        {
                            multiJointManager.RegisterMultiJoint(partsCrossed[k], newJoint);
                        }
                    }

                    if (p.symmetryCounterparts != null && p.symmetryCounterparts.Count > 0)
                    {
                        Part    linkPart = null;
                        Vector3 center   = p.transform.position;
                        float   cross    = float.NegativeInfinity;
                        for (int k = 0; k < p.symmetryCounterparts.Count; k++)
                        {
                            center += p.symmetryCounterparts[k].transform.position;
                        }
                        center /= (p.symmetryCounterparts.Count + 1);

                        for (int k = 0; k < p.symmetryCounterparts.Count; k++)
                        {
                            Part counterPart = p.symmetryCounterparts[k];
                            if (counterPart.parent == p.parent && counterPart.rb != null)
                            {
                                float tmpCross = Vector3.Dot(Vector3.Cross(center - p.transform.position, counterPart.transform.position - p.transform.position), p.transform.up);
                                if (tmpCross > cross)
                                {
                                    cross    = tmpCross;
                                    linkPart = counterPart;
                                }
                            }
                        }
                        if (linkPart)
                        {
                            Rigidbody rigidBody = linkPart.rb;
                            if (!linkPart.rb)
                            {
                                continue;
                            }
                            ConfigurableJoint newJoint;

                            newJoint = p.gameObject.AddComponent <ConfigurableJoint>();

                            newJoint.connectedBody = rigidBody;
                            newJoint.anchor        = Vector3.zero;
                            newJoint.axis          = Vector3.right;
                            newJoint.secondaryAxis = Vector3.forward;
                            newJoint.breakForce    = KJRJointUtils.decouplerAndClampJointStrength;
                            newJoint.breakTorque   = KJRJointUtils.decouplerAndClampJointStrength;

                            newJoint.xMotion        = newJoint.yMotion = newJoint.zMotion = ConfigurableJointMotion.Locked;
                            newJoint.angularXMotion = newJoint.angularYMotion = newJoint.angularZMotion = ConfigurableJointMotion.Locked;

                            multiJointManager.RegisterMultiJoint(p, newJoint);
                            multiJointManager.RegisterMultiJoint(linkPart, newJoint);
                        }
                    }
                }

                if (KJRJointUtils.debug)
                {
                    debugString.AppendLine("Updated joint from " + p.partInfo.title + " to " + p.parent.partInfo.title);
                    debugString.AppendLine("  " + p.partInfo.name + " (" + p.flightID + ") -> " + p.parent.partInfo.name + " (" + p.parent.flightID + ")");
                    debugString.AppendLine("");
                    debugString.AppendLine(p.partInfo.title + " Inertia Tensor: " + p.rb.inertiaTensor + " " + p.parent.partInfo.name + " Inertia Tensor: " + connectedBody.inertiaTensor);
                    debugString.AppendLine("");


                    debugString.AppendLine("Std. Joint Parameters");
                    debugString.AppendLine("Connected Body: " + p.attachJoint.Joint.connectedBody);
                    debugString.AppendLine("Attach mode: " + p.attachMode + " (was " + jointType + ")");
                    if (attach != null)
                    {
                        debugString.AppendLine("Attach node: " + attach.id + " - " + attach.nodeType + " " + attach.size);
                    }
                    if (p_attach != null)
                    {
                        debugString.AppendLine("Parent node: " + p_attach.id + " - " + p_attach.nodeType + " " + p_attach.size);
                    }
                    debugString.AppendLine("Anchor: " + p.attachJoint.Joint.anchor);
                    debugString.AppendLine("Axis: " + p.attachJoint.Joint.axis);
                    debugString.AppendLine("Sec Axis: " + p.attachJoint.Joint.secondaryAxis);
                    debugString.AppendLine("Break Force: " + p.attachJoint.Joint.breakForce);
                    debugString.AppendLine("Break Torque: " + p.attachJoint.Joint.breakTorque);
                    debugString.AppendLine("");

                    debugString.AppendLine("Joint Motion Locked: " + Convert.ToString(p.attachJoint.Joint.xMotion == ConfigurableJointMotion.Locked));

                    debugString.AppendLine("Angular Drive");
                    debugString.AppendLine("Position Spring: " + angDrive.positionSpring);
                    debugString.AppendLine("Position Damper: " + angDrive.positionDamper);
                    debugString.AppendLine("Max Force: " + angDrive.maximumForce);
                    debugString.AppendLine("Mode: " + angDrive.mode);
                    debugString.AppendLine("");

                    debugString.AppendLine("Cross Section Properties");
                    debugString.AppendLine("Radius: " + radius);
                    debugString.AppendLine("Area: " + area);
                    debugString.AppendLine("Moment of Inertia: " + momentOfInertia);
                }
            }
            if (KJRJointUtils.debug)
            {
                Debug.Log(debugString.ToString());
            }
        }
Esempio n. 7
0
        protected override bool DetectSetup()
        {
            finalDirection = (direction == Direction.autodetect) ? DetectDirection() : direction;
            if (finalDirection == Direction.autodetect)
            {
                return(false);
            }

            // determin sub-direction depending on handle
            Bounds handleBounds = Utilities.GetBounds(getHandle().transform, transform);
            Bounds bodyBounds   = Utilities.GetBounds(getBody().transform, transform);

            switch (finalDirection)
            {
            case Direction.x:
                subDirection = (handleBounds.center.x > bodyBounds.center.x) ? -1 : 1;
                pullDistance = bodyBounds.extents.x;
                break;

            case Direction.y:
                subDirection = (handleBounds.center.y > bodyBounds.center.y) ? -1 : 1;
                pullDistance = bodyBounds.extents.y;
                break;

            case Direction.z:
                subDirection = (handleBounds.center.z > bodyBounds.center.z) ? -1 : 1;
                pullDistance = bodyBounds.extents.z;
                break;
            }

            if (body & handle)
            {
                // handle should be outside body hierarchy, otherwise anchor-by-bounds calculation is off
                if (handle.transform.IsChildOf(body.transform))
                {
                    return(false);
                }
            }

            if (cjCreated)
            {
                cj.xMotion = ConfigurableJointMotion.Locked;
                cj.yMotion = ConfigurableJointMotion.Locked;
                cj.zMotion = ConfigurableJointMotion.Locked;

                switch (finalDirection)
                {
                case Direction.x:
                    cj.axis    = Vector3.right;
                    cj.xMotion = ConfigurableJointMotion.Limited;
                    break;

                case Direction.y:
                    cj.axis    = Vector3.up;
                    cj.yMotion = ConfigurableJointMotion.Limited;
                    break;

                case Direction.z:
                    cj.axis    = Vector3.forward;
                    cj.zMotion = ConfigurableJointMotion.Limited;
                    break;
                }
                cj.anchor = cj.axis * (-subDirection * pullDistance);
            }
            if (cj)
            {
                cj.angularXMotion = ConfigurableJointMotion.Locked;
                cj.angularYMotion = ConfigurableJointMotion.Locked;
                cj.angularZMotion = ConfigurableJointMotion.Locked;

                pullDistance *= 1.8f; // don't let it pull out completely

                SoftJointLimit limit = cj.linearLimit;
                limit.limit    = pullDistance;
                cj.linearLimit = limit;
            }
            if (cfCreated)
            {
                cf.force = getThirdDirection(cj.axis, cj.secondaryAxis) * subDirection * -50f;
            }

            return(true);
        }
		private void INTERNAL_get_angularZLimit(out SoftJointLimit value){}
Esempio n. 9
0
    //Sets the weapon to its desired state
    public void SetWeaponState()
    {
        Collider[] colliders = GetComponentsInChildren <Collider>();
        joints = GetComponents <ConfigurableJoint>();
        Rigidbody[] bodies = GetComponentsInChildren <Rigidbody>();

        switch (currentWeaponState)
        {
        //Dropped, no collision, floats and can be picked up
        case WEAPON_STATE.DROPPED:
            canTake = true;
            for (int i = 1; i <= colliders.Length - 1; i++)
            {
                colliders[i].enabled = false;
            }
            for (int i = 0; i < joints.Length; i++)
            {
                joints[i].connectedBody = null;
            }
            GetComponent <BoxCollider>().enabled = true;
            transform.parent = null;
            foreach (Rigidbody body in bodies)
            {
                body.isKinematic = true;
                body.useGravity  = false;
            }
            dropLight.enabled     = true;
            dropAnimation.enabled = true;
            transform.eulerAngles = new Vector3(0, 0, 0);
            equipped = false;

            break;

        //Wielded, collision and rigidbodies enabled, animations and lights disabled
        case WEAPON_STATE.WIELDED:
            canTake = false;
            if (FixMovement == true)
            {
                MovementFixer();
            }
            GetComponent <BoxCollider>().enabled = false;
            for (int i = 0; i < joints.Length; i++)
            {
                joints[i].xMotion        = ConfigurableJointMotion.Limited;
                joints[i].yMotion        = ConfigurableJointMotion.Limited;
                joints[i].zMotion        = ConfigurableJointMotion.Limited;
                joints[i].angularXMotion = ConfigurableJointMotion.Limited;
                joints[i].angularYMotion = ConfigurableJointMotion.Limited;
                joints[i].angularZMotion = ConfigurableJointMotion.Limited;
                SoftJointLimit limit = joints[i].linearLimit;
                limit.limit           = 0;
                joints[i].linearLimit = limit;
            }
            StartCoroutine("CollidersOn");
            foreach (Rigidbody body in bodies)
            {
                body.isKinematic = false;
                body.useGravity  = true;
            }
            foreach (WeaponDamage wd in damageDealers)
            {
                wd.ownHP = wd.FindOwnHP();
            }
            dropLight.enabled     = false;
            dropAnimation.enabled = false;
            equipped = true;
            timer    = true;
            break;

        //Thrown, colliders and rigidbodies enabled, joints free for all kind of movement
        case WEAPON_STATE.THROWN:
            canTake = false;

            for (int i = 1; i <= colliders.Length - 1; i++)
            {
                colliders[i].enabled = true;
            }
            for (int i = 0; i < joints.Length; i++)
            {
                joints[i].connectedBody  = null;
                joints[i].xMotion        = ConfigurableJointMotion.Free;
                joints[i].yMotion        = ConfigurableJointMotion.Free;
                joints[i].zMotion        = ConfigurableJointMotion.Free;
                joints[i].angularXMotion = ConfigurableJointMotion.Free;
                joints[i].angularYMotion = ConfigurableJointMotion.Free;
                joints[i].angularZMotion = ConfigurableJointMotion.Free;
                joints[i].autoConfigureConnectedAnchor = true;
            }
            GetComponent <BoxCollider>().enabled = true;
            transform.parent = null;
            foreach (Rigidbody body in bodies)
            {
                body.isKinematic = false;
                body.useGravity  = true;
            }

            break;
        }
    }
Esempio n. 10
0
        protected override bool DetectSetup()
        {
            finalDirection = (direction == Direction.autodetect ? DetectDirection() : direction);
            if (finalDirection == Direction.autodetect)
            {
                return(false);
            }

            // determin sub-direction depending on handle
            Bounds handleBounds = VRTK_SharedMethods.GetBounds(GetHandle().transform, transform);
            Bounds bodyBounds   = VRTK_SharedMethods.GetBounds(GetBody().transform, transform);

            switch (finalDirection)
            {
            case Direction.x:
                subDirection = (handleBounds.center.x > bodyBounds.center.x) ? -1 : 1;
                pullDistance = bodyBounds.extents.x;
                break;

            case Direction.y:
                subDirection = (handleBounds.center.y > bodyBounds.center.y) ? -1 : 1;
                pullDistance = bodyBounds.extents.y;
                break;

            case Direction.z:
                subDirection = (handleBounds.center.z > bodyBounds.center.z) ? -1 : 1;
                pullDistance = bodyBounds.extents.z;
                break;
            }

            if (body & handle)
            {
                // handle should be outside body hierarchy, otherwise anchor-by-bounds calculation is off
                if (handle.transform.IsChildOf(body.transform))
                {
                    return(false);
                }
            }

            if (drawerJointCreated)
            {
                drawerJoint.xMotion = ConfigurableJointMotion.Locked;
                drawerJoint.yMotion = ConfigurableJointMotion.Locked;
                drawerJoint.zMotion = ConfigurableJointMotion.Locked;

                switch (finalDirection)
                {
                case Direction.x:
                    drawerJoint.axis    = Vector3.right;
                    drawerJoint.xMotion = ConfigurableJointMotion.Limited;
                    break;

                case Direction.y:
                    drawerJoint.axis    = Vector3.up;
                    drawerJoint.yMotion = ConfigurableJointMotion.Limited;
                    break;

                case Direction.z:
                    drawerJoint.axis    = Vector3.forward;
                    drawerJoint.zMotion = ConfigurableJointMotion.Limited;
                    break;
                }
                drawerJoint.anchor = drawerJoint.axis * (-subDirection * pullDistance);
            }
            if (drawerJoint)
            {
                drawerJoint.angularXMotion = ConfigurableJointMotion.Locked;
                drawerJoint.angularYMotion = ConfigurableJointMotion.Locked;
                drawerJoint.angularZMotion = ConfigurableJointMotion.Locked;

                pullDistance *= (maxExtend * 1.8f); // don't let it pull out completely

                SoftJointLimit drawerJointLimit = drawerJoint.linearLimit;
                drawerJointLimit.limit  = pullDistance;
                drawerJoint.linearLimit = drawerJointLimit;

                if (connectedTo)
                {
                    drawerJoint.connectedBody = connectedTo.GetComponent <Rigidbody>();
                }
            }
            if (drawerSnapForceCreated)
            {
                drawerSnapForce.force = GetThirdDirection(drawerJoint.axis, drawerJoint.secondaryAxis) * (subDirection * -50f);
            }

            return(true);
        }
Esempio n. 11
0
    private void FixedUpdate()
    {
        this.IgnoreCollisions();
        switch (this.m_State)
        {
        case GrapplingHook.State.WindedUp:
            if (!this.m_Visualization.activeSelf && Time.time - this.m_plungerTimer > this.m_plungerResetTimer)
            {
                this.PlaySound(WPFMonoBehaviour.gameData.commonAudioCollection.grapplingHookReset);
                this.m_Visualization.SetActive(true);
            }
            break;

        case GrapplingHook.State.Shoot:
            if (this.m_GrapplingHookScript.GetAttachType() != Hook.AttachType.None)
            {
                this.m_State        = GrapplingHook.State.Winding;
                this.m_hookDistance = this.HookDistance();
                Singleton <AudioManager> .Instance.SpawnOneShotEffect(WPFMonoBehaviour.gameData.commonAudioCollection.grapplingHookAttach, this.m_GrapplingHook.transform.position);

                this.m_loopingReelSound = Singleton <AudioManager> .Instance.SpawnLoopingEffect(WPFMonoBehaviour.gameData.commonAudioCollection.grapplingHookReeling, base.transform);

                SoftJointLimit linearLimit = this.m_joint.linearLimit;
                linearLimit.limit        = this.m_hookDistance;
                this.m_joint.linearLimit = linearLimit;
            }
            else if ((this.m_GrapplingHookScript.GetAttachType() == Hook.AttachType.None && this.HookDistance() > this.m_maxHookDistance) || Time.time - this.m_shotStartTime > this.m_ShootTime)
            {
                Singleton <AudioManager> .Instance.SpawnOneShotEffect(WPFMonoBehaviour.gameData.commonAudioCollection.grapplingHookMiss, base.transform.position);

                this.m_ReWindingStartTime = Time.time;
                this.m_State = GrapplingHook.State.Rewind;
            }
            break;

        case GrapplingHook.State.Winding:
        {
            float num = this.HookDistance();
            if (base.contraption.IsConnectedToPig(this, base.GetComponent <Collider>()))
            {
                base.contraption.SetHangingFromHook(true, base.GetInstanceID());
            }
            else
            {
                base.contraption.SetHangingFromHook(false, base.GetInstanceID());
            }
            if (num < this.m_minimumDistance)
            {
                if (this.m_loopingReelSound != null)
                {
                    Singleton <AudioManager> .Instance.StopLoopingEffect(this.m_loopingReelSound.GetComponent <AudioSource>());
                }
                if (this.m_joint != null)
                {
                    SoftJointLimit linearLimit2 = this.m_joint.linearLimit;
                    linearLimit2.limit       = this.m_minimumDistance;
                    this.m_joint.linearLimit = linearLimit2;
                    this.m_joint.zMotion     = ConfigurableJointMotion.Locked;
                    this.m_joint.xMotion     = ConfigurableJointMotion.Limited;
                    this.m_joint.yMotion     = ConfigurableJointMotion.Limited;
                }
            }
            else if (this.m_GrapplingHookScript != null && this.m_GrapplingHookScript.GetAttachType() != Hook.AttachType.None)
            {
                if ((double)num > 1.1 * (double)this.m_maxHookDistance)
                {
                    this.PlaySound(WPFMonoBehaviour.gameData.commonAudioCollection.grapplingHookDetach);
                    this.m_State = GrapplingHook.State.Rewind;
                    base.contraption.SetHangingFromHook(false, base.GetInstanceID());
                }
                else
                {
                    this.m_joint.zMotion = ConfigurableJointMotion.Locked;
                    this.m_joint.xMotion = ConfigurableJointMotion.Limited;
                    this.m_joint.yMotion = ConfigurableJointMotion.Limited;
                    if (this.m_minimumDistance < num)
                    {
                        SoftJointLimit linearLimit3 = this.m_joint.linearLimit;
                        linearLimit3.limit -= this.m_maxWindingSpeed * Time.fixedDeltaTime;
                        if (linearLimit3.limit < this.m_minimumDistance)
                        {
                            linearLimit3.limit = this.m_minimumDistance;
                            if (this.m_loopingReelSound != null)
                            {
                                Singleton <AudioManager> .Instance.StopLoopingEffect(this.m_loopingReelSound.GetComponent <AudioSource>());
                            }
                        }
                        this.m_joint.linearLimit = linearLimit3;
                    }
                }
            }
            break;
        }

        case GrapplingHook.State.Rewind:
            if (this.m_joint != null)
            {
                if (this.m_loopingReelSound != null)
                {
                    Singleton <AudioManager> .Instance.StopLoopingEffect(this.m_loopingReelSound.GetComponent <AudioSource>());
                }
                if (Time.time - this.m_ReWindingStartTime < this.m_rewindingTime && this.HookDistance() > 1f)
                {
                    this.m_GrapplingHookScript.Reset();
                    this.m_GrapplingHookRigidbody.AddForceAtPosition((base.transform.position - this.m_GrapplingHook.transform.position).normalized * 40f, this.m_GrapplingHook.transform.position, ForceMode.Force);
                    float magnitude = this.m_GrapplingHookRigidbody.velocity.magnitude;
                    this.m_GrapplingHookRigidbody.velocity = (base.transform.position - this.m_GrapplingHook.transform.position).normalized * magnitude;
                }
                else
                {
                    this.m_State = GrapplingHook.State.Detach;
                }
            }
            break;

        case GrapplingHook.State.Detach:
            if (this.m_loopingReelSound != null)
            {
                Singleton <AudioManager> .Instance.StopLoopingEffect(this.m_loopingReelSound.GetComponent <AudioSource>());
            }
            this.m_State   = GrapplingHook.State.WindedUp;
            this.m_enabled = false;
            this.InitializeGrapplingHook();
            this.m_GrapplingHookRigidbody.velocity = Vector3.zero;
            this.m_GrapplingHookScript.Reset();
            this.m_plungerTimer = Time.time;
            break;
        }
        if (base.contraption != null && base.contraption.GetTouchingGround())
        {
            base.contraption.SetTouchingGround(false);
            base.contraption.SetSwings(0);
        }
    }
Esempio n. 12
0
        public void CreatePhysicsObjects()
        {
            if (_umaData == null)
            {
                _umaData = gameObject.GetComponent <UMAData> ();
            }

            if (_umaData == null)
            {
                Debug.LogError("CreatePhysicsObjects: umaData is null!");
                return;
            }

            //Don't update if we already have a rigidbody on the root bone?
            if (_rootBone && _rootBone.GetComponent <Rigidbody> ())
            {
                return;
            }

            if (simplePlayerCollider)
            {
                _playerCollider  = gameObject.GetComponent <CapsuleCollider> ();
                _playerRigidbody = gameObject.GetComponent <Rigidbody> ();
                if (_playerCollider == null || _playerRigidbody == null)
                {
                    Debug.LogWarning("PlayerCollider or PlayerRigidBody is null, try putting the collider recipe before the PhysicsRecipe, or turn off SimplePlayerCollider.");
                }
            }

            foreach (UMAPhysicsElement element in elements)
            {
                if (element != null)
                {
                    // add Generic Info
                    GameObject bone = _umaData.GetBoneGameObject(element.boneName);

                    if (bone == null)
                    {
                        Debug.LogWarning("UMAPhysics: " + element.boneName + " not found!");
                        continue; //if we don't find the bone then go to the next iteration
                    }

                    if (!bone.GetComponent <Rigidbody>())
                    {
                        Rigidbody rigidBody = bone.AddComponent <Rigidbody>();
                        rigidBody.isKinematic = true;
                        rigidBody.mass        = element.mass;
                        _rigidbodies.Add(rigidBody);
                    }

                    bone.layer = ragdollLayer;

                    foreach (ColliderDefinition collider in element.colliders)
                    {
                        // Add Appropriate Collider
                        if (collider.colliderType == ColliderDefinition.ColliderType.Box)
                        {
                            BoxCollider boxCollider = bone.AddComponent <BoxCollider>();
                            boxCollider.center    = collider.colliderCentre;
                            boxCollider.size      = collider.boxDimensions;
                            boxCollider.isTrigger = false; //Set initially to false;
                            _BoxColliders.Add(boxCollider);
                        }
                        else if (collider.colliderType == ColliderDefinition.ColliderType.Sphere)
                        {
                            SphereCollider sphereCollider = bone.AddComponent <SphereCollider>();
                            sphereCollider.center    = collider.colliderCentre;
                            sphereCollider.radius    = collider.sphereRadius;
                            sphereCollider.isTrigger = false; //Set initially to false;

                            _SphereColliders.Add(new ClothSphereColliderPair(sphereCollider));
                        }
                        else if (collider.colliderType == ColliderDefinition.ColliderType.Capsule)
                        {
                            CapsuleCollider capsuleCollider = bone.AddComponent <CapsuleCollider>();
                            capsuleCollider.center    = collider.colliderCentre;
                            capsuleCollider.radius    = collider.capsuleRadius;
                            capsuleCollider.height    = collider.capsuleHeight;
                            capsuleCollider.isTrigger = false; //Set initially to false;
                            switch (collider.capsuleAlignment)
                            {
                            case (ColliderDefinition.Direction.X):
                                capsuleCollider.direction = 0;
                                break;

                            case (ColliderDefinition.Direction.Y):
                                capsuleCollider.direction = 1;
                                break;

                            case (ColliderDefinition.Direction.Z):
                                capsuleCollider.direction = 2;
                                break;

                            default:
                                capsuleCollider.direction = 0;
                                break;
                            }
                            _CapsuleColliders.Add(capsuleCollider);
                        }
                    }
                }
            }

            //Second pass to make sure Rigidbodies are all created
            foreach (UMAPhysicsElement element in elements)
            {
                if (element != null)
                {
                    // Make Temp SoftJoint
                    SoftJointLimit tempLimit = new SoftJointLimit();

                    GameObject bone = _umaData.GetBoneGameObject(element.boneName);

                    if (bone == null)
                    {
                        continue; //if we don't find the bone then go to the next iteration
                    }
                    // Add Character Joint
                    if (!element.isRoot)
                    {
                        CharacterJoint joint = bone.AddComponent <CharacterJoint> ();
                        _rootBone                 = bone;
                        joint.connectedBody       = _umaData.GetBoneGameObject(element.parentBone).GetComponent <Rigidbody> ();                  // possible error if parent not yet created.
                        joint.axis                = element.axis;
                        joint.swingAxis           = element.swingAxis;
                        tempLimit.limit           = element.lowTwistLimit;
                        joint.lowTwistLimit       = tempLimit;
                        tempLimit.limit           = element.highTwistLimit;
                        joint.highTwistLimit      = tempLimit;
                        tempLimit.limit           = element.swing1Limit;
                        joint.swing1Limit         = tempLimit;
                        tempLimit.limit           = element.swing2Limit;
                        joint.swing2Limit         = tempLimit;
                        joint.enablePreprocessing = element.enablePreprocessing;
                    }
                }
            }

            UpdateClothColliders();
            SetRagdolled(_ragdolled);
        }
        void DoAction()
        {
            if (cj == null)
            {
                if (!OrComponent.IsNone)
                {
                    cj = OrComponent.Value as ConfigurableJoint;
                }
                else
                {
                    GameObject go = Fsm.GetOwnerDefaultTarget(gameObject);

                    if (go == null)
                    {
                        return;
                    }

                    cj = go.GetComponent <ConfigurableJoint> ();
                }
            }


            if (cj == null)
            {
                return;
            }

            SoftJointLimit sj = new SoftJointLimit();

                        #if !UNITY_PRE_5_1
            SoftJointLimitSpring sp = new SoftJointLimitSpring();
                        #endif
            sj.bounciness = bounciness.Value;
                        #if !UNITY_PRE_5_1
            sj.contactDistance = contactDistance.Value;
                        #endif
            sj.limit = limit.Value;

                        #if !UNITY_PRE_5_1
            sp.damper = damper.Value;
            sp.spring = spring.Value;
                        #else
            sj.damper = damper.Value;
            sj.spring = spring.Value;
                        #endif
            //
            switch (limitType)
            {
            case Limits.Linear:
            {
                cj.linearLimit = sj;
                                #if !UNITY_PRE_5_1
                cj.linearLimitSpring = sp;
                                #endif
            }
            break;

            case Limits.AngularY:
            {
                cj.angularYLimit = sj;
                                #if !UNITY_PRE_5_1
                cj.angularYZLimitSpring = sp;
                                #endif
            }
            break;

            case Limits.AngularZ:
            {
                cj.angularZLimit = sj;
                                #if !UNITY_PRE_5_1
                cj.angularYZLimitSpring = sp;
                                #endif
            }
            break;

            case Limits.AngularXHigh:
            {
                cj.highAngularXLimit = sj;
                                #if !UNITY_PRE_5_1
                cj.angularXLimitSpring = sp;
                                #endif
            }
            break;

            case Limits.AngularXLow:
            {
                cj.lowAngularXLimit = sj;
                                #if !UNITY_PRE_5_1
                cj.angularXLimitSpring = sp;
                                #endif
            }
            break;
            }
            //
        }
Esempio n. 14
0
		private void INTERNAL_get_linearLimit(out SoftJointLimit value){}
        private void SetupSwingBones(List <string> swingBoneNames)
        {
            try
            {
                SoftJointLimit zeroJointLimit  = new SoftJointLimit();
                SoftJointLimit sixtyJointLimit = new SoftJointLimit();
                sixtyJointLimit.limit = 60;

                SwingBones = new Transform[swingBoneNames.Count];

                // Add rigidbody, colliders, characterJoints to bone.
                for (int i = 0; i < swingBoneNames.Count; i++)
                {
                    string    s = swingBoneNames[i];
                    Transform t = umaData.skeleton.GetBoneTransform(UMAUtils.StringToHash(s));
                    SwingBones[i] = t;

                    if (t == null)
                    {
                        Debug.Log("Transform for Swingbone " + s + " not found");
                        continue;
                    }

                    GameObject go = t.gameObject;
                    go.layer = 8;     // our ragdoll layer

                    if (go.GetComponent <Rigidbody>() != null)
                    {
                        continue;
                    }
                    Rigidbody r = go.AddComponent <Rigidbody>();
                    r.isKinematic = false;

                    // Only add gravity to the last link in the chain (the "Pendulum"). Helps prevent physics explosion.
                    if (i == SwingBones.Length - 1)
                    {
                        // this is the Pendulum. Needs gravity. Need script to apply global force
                        r.useGravity = true;
                        //
                        r.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
                        UMAGlobalForceApplier GFA = go.AddComponent <UMAGlobalForceApplier>();
                        GFA.ApplyGlobalForces  = ApplyGlobalForces;
                        GFA.ForceMultiplier    = ForceMultiplier;
                        GFA.MinGlobalForce     = MinGlobalForce;
                        GFA.MaxGlobalForce     = MaxGlobalForce;
                        GFA.MovementTracker    = AnchorBone;
                        GFA.AttachedRigidBody  = r;
                        GFA.parentPosLastFrame = AnchorBone.position;
                    }
                    else
                    {
                        r.useGravity = false;
                    }

                    r.maxAngularVelocity       = 4;
                    r.maxDepenetrationVelocity = 3;
                    r.mass        = SwingMass;
                    r.drag        = SwingDrag;
                    r.angularDrag = SwingAngularDrag;

                    if (FreezePositions)
                    {
                        r.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezePositionZ;
                    }

                    SphereCollider sc = t.gameObject.AddComponent <SphereCollider>();
                    sc.radius = SwingRadius;

                    CharacterJoint c = t.gameObject.AddComponent <CharacterJoint>();

                    c.autoConfigureConnectedAnchor = true;
                    if (i == 0)
                    {
                        c.connectedBody = AnchorBone.gameObject.GetComponent <Rigidbody>();
                    }
                    else
                    {
                        c.connectedBody = SwingBones[i - 1].gameObject.GetComponent <Rigidbody>();
                    }
                    c.lowTwistLimit  = zeroJointLimit;
                    c.highTwistLimit = zeroJointLimit;
                    c.swing1Limit    = sixtyJointLimit;
                    c.swing2Limit    = sixtyJointLimit;
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
            }
        }
Esempio n. 16
0
		private void INTERNAL_get_highAngularXLimit(out SoftJointLimit value){}
Esempio n. 17
0
        protected override bool DetectSetup()
        {
            finalDirection = (direction == ButtonDirection.autodetect ? DetectDirection() : direction);
            if (finalDirection == ButtonDirection.autodetect)
            {
                activationDir = Vector3.zero;
                return(false);
            }
            if (direction != ButtonDirection.autodetect)
            {
                activationDir = CalculateActivationDir();
            }

            if (buttonForce)
            {
                buttonForce.force = GetForceVector();
            }

            if (Application.isPlaying)
            {
                buttonJoint = GetComponent <ConfigurableJoint>();

                bool      recreate  = false;
                Rigidbody oldBody   = null;
                Vector3   oldAnchor = Vector3.zero;
                Vector3   oldAxis   = Vector3.zero;

                if (buttonJoint)
                {
                    // save old values, needs to be recreated
                    oldBody   = buttonJoint.connectedBody;
                    oldAnchor = buttonJoint.anchor;
                    oldAxis   = buttonJoint.axis;
                    DestroyImmediate(buttonJoint);
                    recreate = true;
                }

                // since limit applies to both directions object needs to be moved halfway to activation before adding joint
                transform.position = transform.position + ((activationDir.normalized * activationDistance) * 0.5f);
                buttonJoint        = gameObject.AddComponent <ConfigurableJoint>();

                if (recreate)
                {
                    buttonJoint.connectedBody = oldBody;
                    buttonJoint.anchor        = oldAnchor;
                    buttonJoint.axis          = oldAxis;
                }
                if (connectedTo)
                {
                    buttonJoint.connectedBody = connectedTo.GetComponent <Rigidbody>();
                }

                SoftJointLimit buttonJointLimits = new SoftJointLimit();
                buttonJointLimits.limit = activationDistance * 0.501f; // set limit to half (since it applies to both directions) and a tiny bit larger since otherwise activation distance might be missed
                buttonJoint.linearLimit = buttonJointLimits;

                buttonJoint.angularXMotion = ConfigurableJointMotion.Locked;
                buttonJoint.angularYMotion = ConfigurableJointMotion.Locked;
                buttonJoint.angularZMotion = ConfigurableJointMotion.Locked;
                buttonJoint.xMotion        = ConfigurableJointMotion.Locked;
                buttonJoint.yMotion        = ConfigurableJointMotion.Locked;
                buttonJoint.zMotion        = ConfigurableJointMotion.Locked;

                switch (finalDirection)
                {
                case ButtonDirection.x:
                case ButtonDirection.negX:
                    if (Mathf.RoundToInt(Mathf.Abs(transform.right.x)) == 1)
                    {
                        buttonJoint.xMotion = ConfigurableJointMotion.Limited;
                    }
                    else if (Mathf.RoundToInt(Mathf.Abs(transform.up.x)) == 1)
                    {
                        buttonJoint.yMotion = ConfigurableJointMotion.Limited;
                    }
                    else if (Mathf.RoundToInt(Mathf.Abs(transform.forward.x)) == 1)
                    {
                        buttonJoint.zMotion = ConfigurableJointMotion.Limited;
                    }
                    break;

                case ButtonDirection.y:
                case ButtonDirection.negY:
                    if (Mathf.RoundToInt(Mathf.Abs(transform.right.y)) == 1)
                    {
                        buttonJoint.xMotion = ConfigurableJointMotion.Limited;
                    }
                    else if (Mathf.RoundToInt(Mathf.Abs(transform.up.y)) == 1)
                    {
                        buttonJoint.yMotion = ConfigurableJointMotion.Limited;
                    }
                    else if (Mathf.RoundToInt(Mathf.Abs(transform.forward.y)) == 1)
                    {
                        buttonJoint.zMotion = ConfigurableJointMotion.Limited;
                    }
                    break;

                case ButtonDirection.z:
                case ButtonDirection.negZ:
                    if (Mathf.RoundToInt(Mathf.Abs(transform.right.z)) == 1)
                    {
                        buttonJoint.xMotion = ConfigurableJointMotion.Limited;
                    }
                    else if (Mathf.RoundToInt(Mathf.Abs(transform.up.z)) == 1)
                    {
                        buttonJoint.yMotion = ConfigurableJointMotion.Limited;
                    }
                    else if (Mathf.RoundToInt(Mathf.Abs(transform.forward.z)) == 1)
                    {
                        buttonJoint.zMotion = ConfigurableJointMotion.Limited;
                    }
                    break;
                }
            }

            return(true);
        }
    // Token: 0x060001EA RID: 490 RVA: 0x000088F0 File Offset: 0x00006AF0
    private bool DoTransformHandles(ref global::AuthorChHit.Rep self, ref global::AuthorChHit.Rep connect)
    {
        if (!self.valid)
        {
            return(false);
        }
        Vector3   v       = self.Flip(this.anchor);
        Vector3   vector  = self.AxisFlip(this.axis);
        Vector3   vector2 = self.AxisFlip(this.swingAxis);
        Matrix4x4 matrix  = global::AuthorShared.Scene.matrix;

        if (connect.valid)
        {
            global::AuthorShared.Scene.matrix = connect.bone.localToWorldMatrix;
            Color color = global::AuthorShared.Scene.color;
            global::AuthorShared.Scene.color = color * new Color(1f, 1f, 1f, 0.4f);
            Vector3 vector3 = connect.bone.InverseTransformPoint(self.bone.position);
            if (vector3 != Vector3.zero)
            {
                global::AuthorShared.Scene.DrawBone(Vector3.zero, Quaternion.LookRotation(vector3), vector3.magnitude, 0.02f, new Vector3(0.05f, 0.05f, 0.5f));
            }
            global::AuthorShared.Scene.color = color;
        }
        global::AuthorShared.Scene.matrix = self.bone.localToWorldMatrix;
        bool result = false;

        if (global::AuthorShared.Scene.PivotDrag(ref v, ref vector))
        {
            result      = true;
            this.anchor = self.Flip(v);
            this.axis   = self.AxisFlip(vector);
        }
        global::AuthorChJoint.Kind kind = this.kind;
        if (kind != global::AuthorChJoint.Kind.Hinge)
        {
            if (kind == global::AuthorChJoint.Kind.Character)
            {
                Color color2 = global::AuthorShared.Scene.color;
                global::AuthorShared.Scene.color = color2 * global::AuthorChJoint.twistColor;
                SoftJointLimit softJointLimit = this.lowTwist;
                SoftJointLimit highTwist      = this.highTwist;
                if (global::AuthorShared.Scene.LimitDrag(v, vector, ref this.twistOffset, ref softJointLimit, ref highTwist))
                {
                    result         = true;
                    this.lowTwist  = softJointLimit;
                    this.highTwist = highTwist;
                }
                global::AuthorShared.Scene.color = color2 * global::AuthorChJoint.swing1Color;
                softJointLimit = this.swing1;
                if (global::AuthorShared.Scene.LimitDrag(v, vector2, ref this.swingOffset1, ref softJointLimit))
                {
                    result      = true;
                    this.swing1 = softJointLimit;
                }
                global::AuthorShared.Scene.color = color2 * global::AuthorChJoint.swing2Color;
                softJointLimit = this.swing2;
                if (global::AuthorShared.Scene.LimitDrag(v, Vector3.Cross(vector2, vector), ref this.swingOffset2, ref softJointLimit))
                {
                    result      = true;
                    this.swing2 = softJointLimit;
                }
                global::AuthorShared.Scene.color = color2;
            }
        }
        else if (this.useLimit)
        {
            JointLimits limit = this.limit;
            if (global::AuthorShared.Scene.LimitDrag(v, vector, ref this.limitOffset, ref limit))
            {
                result     = true;
                this.limit = limit;
            }
        }
        global::AuthorShared.Scene.matrix = matrix;
        return(result);
    }
Esempio n. 19
0
    CharacterJoint AddJoint(GameObject joint, int jointIndex)
    {
        CharacterJoint cJoint = joint.AddComponent <CharacterJoint>();

        cJoint.axis      = jointSettings.CJoint_axis;
        cJoint.swingAxis = jointSettings.CJoint_swingAxis;
#if UNITY_2_6
        SoftJointLimit sj = new SoftJointLimit();
        sj.limit              = jointSettings.CJoint_lowTwist_Limit;
        sj.bouncyness         = jointSettings.CJoint_lowTwist_Bounce;
        sj.spring             = jointSettings.CJoint_lowTwist_Spring;
        sj.damper             = jointSettings.CJoint_lowTwist_Dampen;
        cJoint.lowTwistLimit  = sj;
        sj.limit              = jointSettings.CJoint_highTwist_Limit;
        sj.bouncyness         = jointSettings.CJoint_highTwist_Bounce;
        sj.spring             = jointSettings.CJoint_highTwist_Spring;
        sj.damper             = jointSettings.CJoint_highTwist_Dampen;
        cJoint.highTwistLimit = sj;
        sj.limit              = jointSettings.CJoint_swing1_Limit;
        sj.bouncyness         = jointSettings.CJoint_swing1_Bounce;
        sj.spring             = jointSettings.CJoint_swing1_Spring;
        sj.damper             = jointSettings.CJoint_swing1_Dampen;
        cJoint.swing1Limit    = sj;
        sj.limit              = jointSettings.CJoint_swing2_Limit;
        sj.bouncyness         = jointSettings.CJoint_swing2_Bounce;
        sj.spring             = jointSettings.CJoint_swing2_Spring;
        sj.damper             = jointSettings.CJoint_swing2_Dampen;
        cJoint.swing2Limit    = sj;
#endif
#if UNITY_3_0
        SoftJointLimit sj = new SoftJointLimit();
        sj.limit              = jointSettings.CJoint_lowTwist_Limit;
        sj.bounciness         = jointSettings.CJoint_lowTwist_Bounce;
        sj.spring             = jointSettings.CJoint_lowTwist_Spring;
        sj.damper             = jointSettings.CJoint_lowTwist_Dampen;
        cJoint.lowTwistLimit  = sj;
        sj.limit              = jointSettings.CJoint_highTwist_Limit;
        sj.bounciness         = jointSettings.CJoint_highTwist_Bounce;
        sj.spring             = jointSettings.CJoint_highTwist_Spring;
        sj.damper             = jointSettings.CJoint_highTwist_Dampen;
        cJoint.highTwistLimit = sj;
        sj.limit              = jointSettings.CJoint_swing1_Limit;
        sj.bounciness         = jointSettings.CJoint_swing1_Bounce;
        sj.spring             = jointSettings.CJoint_swing1_Spring;
        sj.damper             = jointSettings.CJoint_swing1_Dampen;
        cJoint.swing1Limit    = sj;
        sj.limit              = jointSettings.CJoint_swing2_Limit;
        sj.bounciness         = jointSettings.CJoint_swing2_Bounce;
        sj.spring             = jointSettings.CJoint_swing2_Spring;
        sj.damper             = jointSettings.CJoint_swing2_Dampen;
        cJoint.swing2Limit    = sj;
#endif

        cJoint.breakForce  = CJoint_breakForce;
        cJoint.breakTorque = CJoint_breakTorque;

        if (jointIndex != -1)
        {
            if (!chainLinkSettings.makeAllWeak)
            {
                if (chainLinkSettings.weakLinkBreakingForce != Mathf.Infinity)
                {
                    for (int i = 0; i < chainLinkSettings.weakLinkIndex.Count; i++)
                    {
                        if (jointIndex == chainLinkSettings.weakLinkIndex[i])
                        {
                            cJoint.breakForce = chainLinkSettings.weakLinkBreakingForce;
                            joint.AddComponent <JointBreaker>().SetParentControl(this);
                        }
                    }
                }
            }
            else
            {
                if (chainLinkSettings.weakLinkBreakingForce != Mathf.Infinity)
                {
                    cJoint.breakForce = chainLinkSettings.weakLinkBreakingForce;
                    joint.AddComponent <JointBreaker>().SetParentControl(this);
                }
            }
        }

        return(cJoint);
    }
    //private string InitSet = "LSP 1.0 0000 LSR 1.0 0000 LSY 1.0 0000 LEP 1.0 0000 LWY 1.0 0000 LWP 1.0 0000 LHY 1.0 0000 LHR 1.0 0000 LHP 1.0 0000 LKP 1.0 0000 LAP 1.0 0000 LAR 1.0 0000 RSP 1.0 0000 RSR 1.0 0000 RSY 1.0 0000 REP 1.0 0000 RWY 1.0 0000 RWP 1.0 0000 RHY 1.0 0000 RHR 1.0 0000 RHP 1.0 0000 RKP 1.0 0000 RAP 1.0 0000 RAR 1.0 0000 NK1 1.0 0000 NK2 1.0 0000 Hip 1.0 0000";
    //public Transform curHullTrans;

    void Start()
    {
        //using (StreamWriter writer = new StreamWriter(path))
        //{
        //    writer.Write(InitSet);
        //    writer.Close();
        //}

        TextAsset   textAsset = (TextAsset)Resources.Load("huboplus.kinbody");
        XmlDocument document  = new XmlDocument();

        document.LoadXml(textAsset.text);

        //XmlDocument document = new XmlDocument();
        //document.Load("Assets/Resources/huboplus.kinbody.xml");

        //XmlNodeList tstprts = document.GetElementsByTagName("testPart"); //go down from kinbody?
        XmlNode kinbody = document.SelectSingleNode("kinbody");
        //XmlNode testParts = kinbody.SelectSingleNode("testParts");
        XmlNodeList bodies           = kinbody.SelectNodes("body");
        XmlNodeList collisionIgnores = kinbody.SelectNodes("adjacent");

        //print(bodies.Count);

        for (int i = 0; i < bodies.Count; i++)
        {
            XmlNode     curPar = bodies.Item(i);
            XmlNodeList geoms  = curPar.SelectNodes("geom");

            Instantiate(GameObject.Find("blank"));

            newBod      = GameObject.Find("blank(Clone)");
            newBod.name = curPar.Attributes["name"].Value;

            for (int j = 0; j < geoms.Count; j++)
            {
                XmlNode curGeom = geoms.Item(j);
                if (curGeom.Attributes["type"].Value == "trimesh")
                {
                    XmlNode render = curGeom.SelectSingleNode("render");
                    XmlNode data   = curGeom.SelectSingleNode("data"); //hull
                    XmlNode transl = curGeom.SelectSingleNode("translation");
                    bodyName = render.InnerText;
                    hullName = data.InnerText;
                    perCount = bodyName.IndexOf(".");
                    bodyName = bodyName.Substring(0, perCount);

                    perCount = hullName.IndexOf(".");
                    hullName = hullName.Substring(0, perCount);

                    //bodyTranslate = transl.InnerText;
                    ////print(bodyName);
                    ////print(bodyTranslate);

                    //{
                    //    space1Count = bodyTranslate.IndexOf(" ");
                    //    traXstr = bodyTranslate.Substring(0, space1Count);
                    //    space2Count = bodyTranslate.Substring(space1Count + 1, bodyTranslate.Length - (space1Count + 1)).IndexOf(" ");
                    //    traYstr = bodyTranslate.Substring(space1Count + 1, space2Count);
                    //    space2Count = space1Count + space2Count;
                    //    traZstr = bodyTranslate.Substring(space2Count + 1, bodyTranslate.Length - (space2Count + 1));

                    //    traX = float.Parse(traXstr);
                    //    traY = float.Parse(traYstr);
                    //    traZ = float.Parse(traZstr);

                    curObj = Resources.Load(bodyName) as GameObject;

                    space1Count = bodyName.IndexOf("_");
                    space2Count = bodyName.Substring(space1Count + 1, bodyName.Length - (space1Count + 1)).IndexOf("_");
                    bodyTag     = bodyName.Substring(0, space1Count + space2Count + 1);

                    curObj      = Instantiate(curObj);
                    curObj.name = bodyName;
                    curObj.tag  = bodyTag;
                    ////////////////////////////

                    curObjTrans = curObj.GetComponent <Transform>();

                    curObj.transform.SetParent(newBod.transform);

                    //curHull = GameObject.Find(hullName);
                    //curHullTrans = curHull.GetComponent<Transform>();


                    pos = new Vector3(traX, traY, traZ);

                    curObjTrans.position = pos;
                    //curHullTrans.position = pos;
                    //}

                    {//////////colliders section
                        curHull = Resources.Load(hullName) as GameObject;

                        curHullMesh = curHull.transform.GetChild(0).GetComponent <MeshFilter>().sharedMesh;



                        curObj.AddComponent <MeshCollider>().inflateMesh = true;
                        //print(curHullMesh.name);
                        curObj.GetComponent <MeshCollider>().sharedMesh = curHullMesh;
                        curObj.GetComponent <MeshCollider>().convex     = true;
                        curObj.GetComponent <MeshCollider>().skinWidth  = 0.000000000000000000001F;
                    }
                }
            }



            //print(curPar.Attributes["name"].Value);
        }

        for (int k = 0; k < bodies.Count; k++)
        {
            XmlNode curPar = bodies.Item(k);

            bodyName = curPar.Attributes["name"].Value;

            curObj = GameObject.Find(bodyName);

            //newBod.AddComponent<Rigidbody>();

            if (curObj.name == "Body_Torso")
            {
                curObj.transform.position = new Vector3(0, 0, 0);
            }
            else
            {
                XmlNode offsetBody = curPar.SelectSingleNode("offsetfrom");
                parentName = offsetBody.InnerText;
                curObj.transform.SetParent(GameObject.Find(parentName).transform);

                //    XmlNodeList translations = curPar.SelectNodes("translation");

                //    {
                //        bodyTranslate = translations.Item(1).InnerText; //parent to current
                //        //print(bodyTranslate);
                //        space1Count = bodyTranslate.IndexOf(" ");
                //        traXstr = bodyTranslate.Substring(0, space1Count);
                //        space2Count = bodyTranslate.Substring(space1Count + 1, bodyTranslate.Length - (space1Count + 1)).IndexOf(" ");
                //        traYstr = bodyTranslate.Substring(space1Count + 1, space2Count);
                //        space2Count = space1Count + space2Count;
                //        traZstr = bodyTranslate.Substring(space2Count + 1, bodyTranslate.Length - (space2Count + 1));

                //        traX = float.Parse(traXstr);
                //        traY = float.Parse(traYstr);
                //        traZ = float.Parse(traZstr);

                //        //curObj.transform.Rotate(rotCor);

                //        curObjTrans = curObj.GetComponent<Transform>();

                //        //curHull = GameObject.Find(hullName);
                //        //curHullTrans = curHull.GetComponent<Transform>();


                //        pos = new Vector3(traX, traY, traZ);

                //        curObjTrans.position = pos;
                //        //curObjTrans.rotation = Quaternion.Euler(Vector3.zero);
                //        //curHullTrans.position = pos;
                //    }
            }
        }

        for (int l = 0; l < bodies.Count; l++)
        {
            XmlNode curPar = bodies.Item(l);

            bodyName = curPar.Attributes["name"].Value;

            curObj = GameObject.Find(bodyName);


            //    XmlNode offsetBody = curPar.SelectSingleNode("offsetfrom");
            //    parentName = offsetBody.InnerText;
            //    curObj.transform.SetParent(GameObject.Find(parentName).transform);

            XmlNodeList translations = curPar.SelectNodes("translation");

            {
                traX = 0;
                traY = 0;
                traZ = 0;
                for (int m = 0; m < translations.Count; m++)
                {
                    bodyTranslate = translations.Item(m).InnerText; //parent to current
                    //print("Ping");                                                //        //print(bodyTranslate);
                    space1Count = bodyTranslate.IndexOf(" ");
                    traXstr     = bodyTranslate.Substring(0, space1Count);
                    space2Count = bodyTranslate.Substring(space1Count + 1, bodyTranslate.Length - (space1Count + 1)).IndexOf(" ");
                    traYstr     = bodyTranslate.Substring(space1Count + 1, space2Count);
                    space2Count = space1Count + space2Count;
                    traZstr     = bodyTranslate.Substring(space2Count + 1, bodyTranslate.Length - (space2Count + 1));

                    traX = float.Parse(traXstr) + traX;
                    traY = float.Parse(traYstr) + traY;
                    traZ = float.Parse(traZstr) + traZ;

                    //        //curObj.transform.Rotate(rotCor);

                    curObjTrans = curObj.GetComponent <Transform>();
                    pos         = new Vector3(traX, traY, traZ);
                }
                //print(bodyName);
                //print(pos);
                //print(traX);
                //print(traY);
                //print(traZ);
                curObjTrans.localPosition = new Vector3(traX, traY, traZ);
                //curObjTrans.rotation = Quaternion.Euler(Vector3.zero);
                //        //curHullTrans.position = pos;
            }
        }



        for (int n = 0; n < bodies.Count; n++)
        {
            {
                XmlNode curPar = bodies.Item(n);

                bodyName = curPar.Attributes["name"].Value;

                curObj = GameObject.Find(bodyName);

                curObj.AddComponent <Rigidbody>().useGravity = false;

                XmlNode mass      = curPar.SelectSingleNode("mass");
                XmlNode totalMass = mass.SelectSingleNode("total");
                XmlNode com       = mass.SelectSingleNode("com");

                massVal = float.Parse(totalMass.InnerText);


                if (com != null)
                {
                    string axisStr = com.InnerText; //parent to current
                    space1Count = axisStr.IndexOf(" ");
                    traXstr     = axisStr.Substring(0, space1Count);
                    space2Count = axisStr.Substring(space1Count + 1, axisStr.Length - (space1Count + 1)).IndexOf(" ");
                    traYstr     = axisStr.Substring(space1Count + 1, space2Count);
                    space2Count = space1Count + space2Count;
                    traZstr     = axisStr.Substring(space2Count + 1, axisStr.Length - (space2Count + 1));


                    massPos.x = float.Parse(traXstr);
                    massPos.y = float.Parse(traYstr);
                    massPos.z = float.Parse(traZstr);
                }

                curObj.GetComponent <Rigidbody>().mass         = massVal;
                curObj.GetComponent <Rigidbody>().centerOfMass = massPos;
            }
        }
        //joint stuff
        XmlNodeList joints = kinbody.SelectNodes("Joint");

        for (int o = 0; o < joints.Count; o++)
        {
            XmlNodeList joinBods = joints.Item(o).SelectNodes("body");

            string jointBody1 = joinBods.Item(0).InnerText;
            string jointBody2 = joinBods.Item(1).InnerText;
            //print(jointBody1);
            //print(jointBody2);



            GameObject child  = GameObject.Find(jointBody2);
            GameObject parent = GameObject.Find(jointBody1);

            {
                if (joints.Item(o).SelectSingleNode("anchor") != null)
                {
                    string anchorStr = joints.Item(o).SelectSingleNode("anchor").InnerText; //parent to current
                    space1Count = anchorStr.IndexOf(" ");
                    traXstr     = anchorStr.Substring(0, space1Count);
                    space2Count = anchorStr.Substring(space1Count + 1, anchorStr.Length - (space1Count + 1)).IndexOf(" ");
                    traYstr     = anchorStr.Substring(space1Count + 1, space2Count);
                    space2Count = space1Count + space2Count;
                    traZstr     = anchorStr.Substring(space2Count + 1, anchorStr.Length - (space2Count + 1));

                    anchX = float.Parse(traXstr);
                    anchY = float.Parse(traYstr);
                    anchZ = float.Parse(traZstr);
                }
            }
            if (joints.Item(o).SelectSingleNode("limitsdeg") != null)
            {
                string limitsStr = joints.Item(o).SelectSingleNode("limitsdeg").InnerText; //parent to current
                space1Count = limitsStr.IndexOf(" ");
                traXstr     = limitsStr.Substring(0, space1Count);
                traYstr     = limitsStr.Substring(space1Count + 1, limitsStr.Length - (space1Count + 1));

                limMin = float.Parse(traXstr);
                limMax = float.Parse(traYstr);
                //print("Low");
                //print(limMin);
                //print("High");
                //print(limMax);
            }
            if (joints.Item(o).SelectSingleNode("axis") != null)
            {
                string axisStr = joints.Item(o).SelectSingleNode("axis").InnerText; //parent to current
                space1Count = axisStr.IndexOf(" ");
                traXstr     = axisStr.Substring(0, space1Count);
                space2Count = axisStr.Substring(space1Count + 1, axisStr.Length - (space1Count + 1)).IndexOf(" ");
                traYstr     = axisStr.Substring(space1Count + 1, space2Count);
                space2Count = space1Count + space2Count;
                traZstr     = axisStr.Substring(space2Count + 1, axisStr.Length - (space2Count + 1));


                axX = Mathf.Abs(int.Parse(traXstr));
                axY = Mathf.Abs(int.Parse(traYstr));
                axZ = Mathf.Abs(int.Parse(traZstr));
            }

            ////////////////////////////////////////
            //addjoint//
            child.AddComponent <ConfigurableJoint>();
            curJoint        = child.GetComponent <ConfigurableJoint>();
            anch            = new Vector3(anchX, anchY, anchZ);
            curJoint.anchor = anch;
            //curJoint.useLimits = true;
            curJoint.xMotion = ConfigurableJointMotion.Locked;
            curJoint.yMotion = ConfigurableJointMotion.Locked;
            curJoint.zMotion = ConfigurableJointMotion.Locked;

            curJoint.angularYMotion = ConfigurableJointMotion.Locked;
            curJoint.angularZMotion = ConfigurableJointMotion.Locked;

            SoftJointLimit limMinSoft = curJoint.lowAngularXLimit;
            limMinSoft.limit          = limMin;
            curJoint.lowAngularXLimit = limMinSoft;

            SoftJointLimit limMaxSoft = curJoint.highAngularXLimit;
            limMaxSoft.limit          = limMax;
            curJoint.lowAngularXLimit = limMaxSoft;

            {
                /*
                 * if (axX != 0)
                 * {
                 *  //print("ping");
                 *  curJoint.angularYMotion = ConfigurableJointMotion.Locked;
                 *  curJoint.angularZMotion = ConfigurableJointMotion.Locked;
                 *  //child.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationY;
                 *  //child.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationZ;
                 * }
                 * else if (axY != 0)
                 * {
                 *  //print("pang");
                 *  curJoint.angularXMotion = ConfigurableJointMotion.Locked;
                 *  curJoint.angularZMotion = ConfigurableJointMotion.Locked;
                 *  //child.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX;
                 *  //child.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationZ;
                 * }
                 *
                 * else if (axZ != 0)
                 * {
                 *  //print("pong");
                 *  curJoint.angularYMotion = ConfigurableJointMotion.Locked;
                 *  curJoint.angularXMotion = ConfigurableJointMotion.Locked;
                 *  //child.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationY;
                 *  //child.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX;
                 * }
                 */
            }

            curJoint.connectedBody = parent.GetComponent <Rigidbody>();
            curJoint.axis          = new Vector3(axX, axY, axZ); /////set AXIS
            //print(curJoint);



            //dont forget to set axis and fix limits
        }



        for (int n = 0; n < bodies.Count; n++)
        {
            {
                XmlNode curPar = bodies.Item(n);

                bodyName = curPar.Attributes["name"].Value;

                curObj = GameObject.Find(bodyName);
                curObj.GetComponent <Rigidbody>().useGravity = true;

                if (bodyName != "Body_Torso")
                {
                    //curObj.AddComponent<TestHUBOJoint4>();
                    curObj.AddComponent <PositionLock>();
                }
            }
        }



        for (int p = 0; p < collisionIgnores.Count; p++)
        {
            string limitsStr = collisionIgnores.Item(p).InnerText; //parent to current
            space1Count = limitsStr.IndexOf(" ");
            col1        = limitsStr.Substring(0, space1Count);
            col2        = limitsStr.Substring(space1Count + 1, limitsStr.Length - (space1Count + 1));

            childObjects1 = GameObject.FindGameObjectsWithTag(col1);
            childObjects2 = GameObject.FindGameObjectsWithTag(col2);


            for (int q = 0; q < childObjects1.Length; q++)
            {
                colObj1 = childObjects1[q];
                for (int r = 0; r < childObjects2.Length; r++)
                {
                    colObj2 = childObjects2[r];
                    Physics.IgnoreCollision(colObj1.GetComponent <MeshCollider>(), colObj2.GetComponent <MeshCollider>(), true);
                }
            }
        }



        GameObject.Find("Body_Torso").transform.Rotate(new Vector3(-90, 0, 0));
        GameObject.Find("Body_Torso").GetComponent <Rigidbody>().isKinematic = true;
    }
Esempio n. 21
0
    private bool DoTransformHandles(ref AuthorChHit.Rep self, ref AuthorChHit.Rep connect)
    {
        if (!self.valid)
        {
            return(false);
        }
        Vector3   anchor  = self.Flip(this.anchor);
        Vector3   axis    = self.AxisFlip(this.axis);
        Vector3   vector3 = self.AxisFlip(this.swingAxis);
        Matrix4x4 matrix  = AuthorShared.Scene.matrix;

        if (connect.valid)
        {
            AuthorShared.Scene.matrix = connect.bone.localToWorldMatrix;
            Color color = AuthorShared.Scene.color;
            AuthorShared.Scene.color = color * new Color(1f, 1f, 1f, 0.4f);
            Vector3 forward = connect.bone.InverseTransformPoint(self.bone.position);
            if (forward != Vector3.zero)
            {
                Quaternion rot = Quaternion.LookRotation(forward);
                AuthorShared.Scene.DrawBone(Vector3.zero, rot, forward.magnitude, 0.02f, new Vector3(0.05f, 0.05f, 0.5f));
            }
            AuthorShared.Scene.color = color;
        }
        AuthorShared.Scene.matrix = self.bone.localToWorldMatrix;
        bool flag = false;

        if (AuthorShared.Scene.PivotDrag(ref anchor, ref axis))
        {
            flag        = true;
            this.anchor = self.Flip(anchor);
            this.axis   = self.AxisFlip(axis);
        }
        switch (this.kind)
        {
        case Kind.Hinge:
            if (this.useLimit)
            {
                JointLimits limits = this.limit;
                if (AuthorShared.Scene.LimitDrag(anchor, axis, ref this.limitOffset, ref limits))
                {
                    flag       = true;
                    this.limit = limits;
                }
            }
            break;

        case Kind.Character:
        {
            Color color2 = AuthorShared.Scene.color;
            AuthorShared.Scene.color = color2 * twistColor;
            SoftJointLimit lowTwist  = this.lowTwist;
            SoftJointLimit highTwist = this.highTwist;
            if (AuthorShared.Scene.LimitDrag(anchor, axis, ref this.twistOffset, ref lowTwist, ref highTwist))
            {
                flag           = true;
                this.lowTwist  = lowTwist;
                this.highTwist = highTwist;
            }
            AuthorShared.Scene.color = color2 * swing1Color;
            lowTwist = this.swing1;
            if (AuthorShared.Scene.LimitDrag(anchor, vector3, ref this.swingOffset1, ref lowTwist))
            {
                flag        = true;
                this.swing1 = lowTwist;
            }
            AuthorShared.Scene.color = color2 * swing2Color;
            lowTwist = this.swing2;
            if (AuthorShared.Scene.LimitDrag(anchor, Vector3.Cross(vector3, axis), ref this.swingOffset2, ref lowTwist))
            {
                flag        = true;
                this.swing2 = lowTwist;
            }
            AuthorShared.Scene.color = color2;
            break;
        }
        }
        AuthorShared.Scene.matrix = matrix;
        return(flag);
    }
Esempio n. 22
0
        //--------------------------------------------------------------------------------------------------------------------------------------------------------------

        private void LinearLimit(Action action)
        {
            Enum <ConfigurableJoint>(j => { _softJointLimit = j.linearLimit; action.Invoke(); j.linearLimit = _softJointLimit; });
        }
Esempio n. 23
0
    public override bool PeiceInspectorGUI()
    {
        bool   flag    = base.PeiceInspectorGUI();
        string peiceID = base.peiceID;

        if (AuthorShared.StringField("Title", ref peiceID, new GUILayoutOption[0]))
        {
            base.peiceID = peiceID;
            flag         = true;
        }
        AuthorShared.EnumField("Kind", this.kind, new GUILayoutOption[0]);
        AuthorShared.PrefixLabel("Self");
        if (GUILayout.Button((GUIContent)AuthorShared.ObjectContent <AuthorChHit>(this.self, typeof(AuthorChHit)), new GUILayoutOption[0]))
        {
            AuthorShared.PingObject(this.self);
        }
        flag |= AuthorShared.PeiceField <AuthorChHit>("Connected", this, ref this.connect, typeof(AuthorChHit), GUI.skin.button, new GUILayoutOption[0]);
        flag |= AuthorShared.Toggle("Reverse Link", ref this.reverseLink, new GUILayoutOption[0]);
        flag |= AuthorShared.Vector3Field("Anchor", ref this.anchor, new GUILayoutOption[0]);
        flag |= AuthorShared.Vector3Field("Axis", ref this.axis, new GUILayoutOption[0]);
        switch (this.kind)
        {
        case Kind.Hinge:
        {
            JointLimits limits = this.limit;
            if (Field("Limits", ref limits, ref this.useLimit, ref this.limitOffset))
            {
                flag       = true;
                this.limit = limits;
            }
            break;
        }

        case Kind.Character:
        {
            flag |= AuthorShared.Vector3Field("Swing Axis", ref this.swingAxis, new GUILayoutOption[0]);
            SoftJointLimit lowTwist = this.lowTwist;
            if (Field("Low Twist", ref lowTwist, ref this.twistOffset))
            {
                flag          = true;
                this.lowTwist = lowTwist;
            }
            lowTwist = this.highTwist;
            if (Field("High Twist", ref lowTwist, ref this.twistOffset))
            {
                flag           = true;
                this.highTwist = lowTwist;
            }
            lowTwist = this.swing1;
            if (Field("Swing 1", ref lowTwist, ref this.swingOffset1))
            {
                flag        = true;
                this.swing1 = lowTwist;
            }
            lowTwist = this.swing2;
            if (Field("Swing 2", ref lowTwist, ref this.swingOffset2))
            {
                flag        = true;
                this.swing2 = lowTwist;
            }
            break;
        }
        }
        flag |= AuthorShared.FloatField("Break Force", ref this.breakForce, new GUILayoutOption[0]);
        return(flag | AuthorShared.FloatField("Break Torque", ref this.breakTorque, new GUILayoutOption[0]));
    }
Esempio n. 24
0
    private Rigidbody Break(Bone b, int mass)
    {
        Rigidbody rb = b.bone.AddComponent <Rigidbody>();

        //rb.gameObject.AddComponent<DeadBody>();
        if (rb)
        {
            rb.mass        = mass;
            rb.isKinematic = false;
            rb.angularDrag = 1;

            //CapsuleCollider cc = b.bone.AddComponent<CapsuleCollider>();
        }
        foreach (Bone bro in b.joints)
        {
            Rigidbody r = Break(bro, mass);

            /*
             * FixedJoint fj = bro.bone.AddComponent<FixedJoint>();
             * fj.connectedBody = rb;*/
            //fj.

            /*
             * SpringJoint sj = bro.bone.AddComponent<SpringJoint>();
             * sj.connectedBody = rb;
             * //sj.autoConfigureConnectedAnchor = false;
             * sj.damper = 10000;
             * sj.spring = 10000;
             * sj.maxDistance = (bro.bone.transform.position - b.bone.transform.position).magnitude+.1f;
             * sj.minDistance = (bro.bone.transform.position - b.bone.transform.position).magnitude-.1f;
             * sj.axis = (bro.bone.transform.position - b.bone.transform.position).normalized * -1;
             */
            CharacterJoint cj = bro.bone.AddComponent <CharacterJoint>();
            cj.axis      = (bro.bone.transform.position - b.bone.transform.position).normalized * -1;
            cj.swingAxis = bro.bone.transform.right;
            SoftJointLimitSpring sjls = new SoftJointLimitSpring();
            sjls.spring = 1000;
            sjls.damper = 10000;
            SoftJointLimit sjl90 = new SoftJointLimit();
            sjl90.bounciness = 0;
            sjl90.limit      = 10;// 35;
            SoftJointLimit sjl0 = new SoftJointLimit();
            sjl0.bounciness     = 00;
            sjl0.limit          = 0;
            cj.swingLimitSpring = sjls;
            cj.twistLimitSpring = sjls;
            cj.swing1Limit      = sjl90;
            cj.swing2Limit      = sjl90;
            cj.highTwistLimit   = sjl0;
            cj.lowTwistLimit    = sjl0;
            cj.connectedBody    = rb;

            /*
             * sj.autoConfigureConnectedAnchor = false;
             * sj.spring = 100;
             * sj.damper = 100;*/
        }

        //Destroy(b.bone.GetComponent<Collider>());
        //b.bone.AddComponent<SphereCollider>();
        //rb.mass = 30;

        /*
         * if(b.joints.Count <= 0 && b.bone.GetComponent<Collider>() == null)
         * {
         *  b.bone.AddComponent<BoxCollider>();
         *  rb.mass = 30;
         * }*/
        return(rb);
    }
    public static void Load(string ragdoll, GameObject target, bool editor)
    {
        Dictionary <string, RagdollJoint> ragdollJointsDictionary = new Dictionary <string, RagdollJoint>();

        RagdollJoint[] ragdollJoints = XMLSerializer.DeserializeObject <Ragdoll>(ragdoll).ragdollJoints;
        foreach (RagdollJoint rJ in ragdollJoints)
        {
            ragdollJointsDictionary[rJ.boneName] = rJ;
        }

        if (ragdollJointsDictionary.ContainsKey(target.name))
        {
            // Root bone

            if (target.GetComponent <CharacterJoint>() != null)
            {
                DestroyImmediate(target.GetComponent <CharacterJoint>());
            }
            if (target.GetComponent <Collider>() != null)
            {
                DestroyImmediate(target.GetComponent <Collider>());
            }
            if (target.GetComponent <Rigidbody>() != null)
            {
                DestroyImmediate(target.GetComponent <Rigidbody>());
            }
            Dictionary <string, GameObject> children = new Dictionary <string, GameObject>();
            foreach (Transform t in target.GetComponentsInChildren <Transform>())
            {
                children[t.gameObject.name] = t.gameObject;

                if (t.gameObject.GetComponent <CharacterJoint>() != null)
                {
                    DestroyImmediate(t.gameObject.GetComponent <CharacterJoint>());
                }
                if (t.gameObject.GetComponent <Collider>() != null)
                {
                    DestroyImmediate(t.gameObject.GetComponent <Collider>());
                }
                if (t.gameObject.GetComponent <Rigidbody>() != null)
                {
                    DestroyImmediate(t.gameObject.GetComponent <Rigidbody>());
                }
            }
            children[target.name] = target;

            RagdollJoint rJ = ragdollJointsDictionary[target.name];

            if (rJ.boxColliderSettings != null)
            {
                BoxCollider bC = target.AddComponent <BoxCollider>();
                bC.center = MathHelper.FromString(rJ.boxColliderSettings.center);
                bC.size   = MathHelper.FromString(rJ.boxColliderSettings.size);
            }
            else if (rJ.sphereColliderSettings != null)
            {
                SphereCollider sC = target.AddComponent <SphereCollider>();
                sC.center = MathHelper.FromString(rJ.sphereColliderSettings.center);
                sC.radius = rJ.sphereColliderSettings.radius;
            }
            else if (rJ.capsuleColliderSettings != null)
            {
                CapsuleCollider cC = target.AddComponent <CapsuleCollider>();
                cC.center    = MathHelper.FromString(rJ.capsuleColliderSettings.center);
                cC.radius    = rJ.capsuleColliderSettings.radius;
                cC.height    = rJ.capsuleColliderSettings.height;
                cC.direction = rJ.capsuleColliderSettings.direction;
            }
            else
            {
                Debug.LogError("Ragdoll Loader: collider type is not supported (" + target.name + ")");
            }

            Rigidbody rB = target.AddComponent <Rigidbody>();
            rB.mass = rJ.rigidbodySettings.mass;

            // Children

            if (editor)
            {
                Debug.Log("Ragdoll Loader: " + target.name + " joint processed");
            }

            int count = 1;

            foreach (GameObject gO in children.Values)
            {
                if (gO.name == target.name)
                {
                    continue;
                }

                if (ragdollJointsDictionary.ContainsKey(gO.name))
                {
                    rJ = ragdollJointsDictionary[gO.name];

                    if (rJ.boxColliderSettings != null)
                    {
                        BoxCollider bC = gO.AddComponent <BoxCollider>();
                        bC.center = MathHelper.FromString(rJ.boxColliderSettings.center);
                        bC.size   = MathHelper.FromString(rJ.boxColliderSettings.size);
                    }
                    else if (rJ.sphereColliderSettings != null)
                    {
                        SphereCollider sC = gO.AddComponent <SphereCollider>();
                        sC.center = MathHelper.FromString(rJ.sphereColliderSettings.center);
                        sC.radius = rJ.sphereColliderSettings.radius;
                    }
                    else if (rJ.capsuleColliderSettings != null)
                    {
                        CapsuleCollider cC = gO.AddComponent <CapsuleCollider>();
                        cC.center    = MathHelper.FromString(rJ.capsuleColliderSettings.center);
                        cC.radius    = rJ.capsuleColliderSettings.radius;
                        cC.height    = rJ.capsuleColliderSettings.height;
                        cC.direction = rJ.capsuleColliderSettings.direction;
                    }
                    else
                    {
                        Debug.LogError("Ragdoll Loader: collider type is not supported (" + gO.name + ")");
                    }

                    rB      = gO.AddComponent <Rigidbody>();
                    rB.mass = rJ.rigidbodySettings.mass;

                    if (editor)
                    {
                        Debug.Log("Ragdoll Loader: " + gO.name + " joint processed");
                    }

                    count++;
                }
                else if (editor)
                {
                    //Debug.LogWarning("AssignRagdoll: bone name not found in ragdoll (" + gO.name + ")");
                }
            }

            foreach (GameObject gO in children.Values)
            {
                if (gO.name == target.name)
                {
                    continue;
                }

                if (ragdollJointsDictionary.ContainsKey(gO.name))
                {
                    rJ = ragdollJointsDictionary[gO.name];

                    CharacterJoint cJ = gO.AddComponent <CharacterJoint>();

                    if (children.ContainsKey(rJ.characterJointSettings.connectedBody))
                    {
                        cJ.connectedBody = children[rJ.characterJointSettings.connectedBody].GetComponent <Rigidbody>();
                    }
                    else
                    {
                        Debug.LogError("Ragdoll Loader: connected joint not found (" + rJ.characterJointSettings.connectedBody + " with " + gO.name + ")");
                    }

                    cJ.anchor          = MathHelper.FromString(rJ.characterJointSettings.anchor);
                    cJ.axis            = MathHelper.FromString(rJ.characterJointSettings.axis);
                    cJ.swingAxis       = MathHelper.FromString(rJ.characterJointSettings.swingAxis);
                    cJ.connectedAnchor = MathHelper.FromString(rJ.characterJointSettings.connectedAnchor);

                    float spring = 225F;
                    float damper = 10F;
                    SoftJointLimitSpring sJLS = new SoftJointLimitSpring();
                    sJLS.damper         = damper;
                    sJLS.spring         = spring;
                    cJ.twistLimitSpring = sJLS;
                    sJLS                = new SoftJointLimitSpring();
                    sJLS.damper         = damper;
                    sJLS.spring         = spring;
                    cJ.swingLimitSpring = sJLS;

                    float bounciness      = .00F; // Joint bounciness when it hits the limit
                    float contactDistance = 0;    // 0 = Default

                    SoftJointLimit sJL = new SoftJointLimit();
                    sJL.bounciness      = bounciness;//rJ.characterJointSettings.lowTwistLimit_Bounciness;
                    sJL.limit           = rJ.characterJointSettings.lowTwistLimit_Limit;
                    sJL.contactDistance = contactDistance;
                    cJ.lowTwistLimit    = sJL;

                    sJL                 = new SoftJointLimit();
                    sJL.bounciness      = bounciness;//rJ.characterJointSettings.highTwistLimit_Bounciness;
                    sJL.limit           = rJ.characterJointSettings.highTwistLimit_Limit;
                    sJL.contactDistance = contactDistance;
                    cJ.highTwistLimit   = sJL;

                    sJL                 = new SoftJointLimit();
                    sJL.bounciness      = bounciness;//rJ.characterJointSettings.swing1Limit_Bounciness;
                    sJL.limit           = rJ.characterJointSettings.swing1Limit_Limit;
                    sJL.contactDistance = contactDistance;
                    cJ.swing1Limit      = sJL;

                    sJL                 = new SoftJointLimit();
                    sJL.bounciness      = bounciness;//rJ.characterJointSettings.swing2Limit_Bounciness;
                    sJL.limit           = rJ.characterJointSettings.swing2Limit_Limit;
                    sJL.contactDistance = contactDistance;
                    cJ.swing2Limit      = sJL;
                }
            }

            if (editor)
            {
                Debug.Log("Ragdoll Loader: " + count.ToString() + " joints processed");
                Debug.Log("Success!");
            }
        }
        else
        {
            Debug.LogError("Ragdoll Loader: target needs to be the root bone!");
        }
    }
Esempio n. 26
0
    // Update is called once per frame
    void FixedUpdate()
    {
        //if (GameObject.Find("0").GetComponent<RoboJoint>().stop && thisStop){
        //	globalCollision(rb);
        //}
        thisStop = true;
        if (firstRun)
        {
            //joint.connectedBody = parent.GetComponent<Rigidbody>();
            //string sliderNo ="Slider (" + (GameObject.Find("0").GetComponent<RoboJoint>().DHTable.Length/2).ToString() + ")";
            Debug.Log(parent);
            otherScale = parent.GetComponent <RoboJoint3>().otherScale;
            this.transform.localScale = new Vector3(otherScale, otherScale, otherScale);
            grabSlider = GameObject.Find(sliderNo).GetComponent <Slider>();
            firstRun   = false;
            Debug.Log(this.transform.localScale.x / 2);
            //this.gameObject.transform.SetParent(parent.transform);
            sizes  = GetDimensions(gameObject);
            sizes2 = GetDimensions(parent);
            Debug.Log((-sizes2.z / 2 - sizes.z / 2) + "    " + (sizes2.z / 2 + sizes.z / 2));
            //Debug.Log(sizes);
            if (this.name == "hand 1")
            {
                this.transform.position = (parent.transform.position + new Vector3(1f + sizes2.x / 2 + sizes.x / 2, 0, -sizes2.z / 2 - sizes.z / 2));
            }

            else if (this.name == "hand 2")
            {
                //this.transform.eulerAngles = new Vector3(180f, 0f,0f);
                this.transform.position = (parent.transform.position + new Vector3(0.1f + sizes2.x / 2 + sizes.x / 2, 0, sizes2.z / 2 + sizes.z / 2));
            }
        }
        if (waitCount == 200)
        {
            //Debug.Log((parent.transform.localScale.x/2 + this.transform.localScale.x/2) + "        " +  (parent.transform.localScale.x/2 + this.transform.localScale.x/2));

            //Debug.Log(sizes.z/2 + "    " + sizes2.z/2);
            sizes  = GetDimensions(gameObject);
            sizes2 = GetDimensions(parent);
            //Debug.Log((parent.transform.position + new Vector3(sizes2.x/2 + sizes.x/2, 0,-sizes2.z/2 - sizes.z/2)) + "    " + (parent.transform.position + new Vector3(0.1f + sizes2.x/2 + sizes.x/2, 0,sizes2.z/2 + sizes.z/2)));
            //Debug.Log(" DEBUG " + (-sizes2.z/2 - sizes.z/2) + "    " + (sizes2.z/2 + sizes.z/2));
            //Debug.Log(sizes);
            if (this.name == "hand 1")
            {
                //this.transform.position = (parent.transform.position + new Vector3(0.15f + sizes2.x/2 + sizes.x/2, 0,-sizes2.z/2 - sizes.z/2));
                //this.transform.position = (parent.transform.position + new Vector3(sizes2.x/2, (-sizes2.y/2 - sizes.y/2)*0.7f,-sizes2.z/2 - sizes.z/2));
                this.transform.position = (parent.transform.position + new Vector3(sizes2.x / 2 * offsets.x, (-sizes2.y / 2 - sizes.y / 2) * offsets.y, -sizes2.z / 2 - sizes.z / 2));
            }

            else if (this.name == "hand 2")
            {
                //this.transform.eulerAngles = new Vector3(180f, 0f,0f);
                //this.transform.position = (parent.transform.position + new Vector3(0.15f + sizes2.x/2 + sizes.x/2, 0, sizes2.z/2 + sizes.z/2));
                //this.transform.position = (parent.transform.position + new Vector3(sizes2.x/2, (-sizes2.y/2 - sizes.y/2)*0.7f, sizes2.z/2 + sizes.z/2));
                this.transform.position = (parent.transform.position + new Vector3(sizes2.x / 2 * offsets.x, (-sizes2.y / 2 - sizes.y / 2) * offsets.y, sizes2.z / 2 + sizes.z / 2));
            }
            rb.isKinematic          = false;
            this.transform.rotation = (parent.transform.rotation);
        }
        if (waitCount >= 200)
        {
            if (cj == null && !justCollided)
            {
                this.transform.rotation = (parent.transform.rotation);
                cj = this.gameObject.AddComponent <ConfigurableJoint>();
                cj.connectedBody = jointParent.GetComponent <Rigidbody>();
                cj.xMotion       = ConfigurableJointMotion.Locked;
                cj.yMotion       = ConfigurableJointMotion.Locked;
                //cj.zMotion = ConfigurableJointMotion.Limited;
                cj.zMotion = ConfigurableJointMotion.Locked;
                SoftJointLimit linLim = new SoftJointLimit();
                linLim.limit       = sizes2.z / 2 * offsets.z;
                cj.linearLimit     = linLim;
                cj.angularXMotion  = ConfigurableJointMotion.Locked;
                cj.angularYMotion  = ConfigurableJointMotion.Locked;
                cj.angularZMotion  = ConfigurableJointMotion.Locked;
                cj.anchor          = new Vector3(0f, 0f, 0f);
                cj.enableCollision = true;
                drive = new JointDrive();
                drive.positionSpring  = 100;
                drive.positionDamper  = 50;
                drive.maximumForce    = 10;
                cj.zDrive             = drive;
                cj.connectedMassScale = 0;
            }
        }
        if (waitCount == 300)
        {
        }
        waitCount++;
        Physics.IgnoreCollision(parent.GetComponent <Collider>(), this.GetComponent <Collider>(), true);

        targetGrab = grabSlider.value; // both these should be created from the robi file
        prevRot    = this.transform.rotation;
        prevPos    = this.transform.position;
        if (grab + 2 <= targetGrab)
        {
            if (!justCollided)
            {
                prevGrab[1] = prevGrab[0];
                prevGrab[0] = grab;
            }
            grab   += 2f;
            prevPos = this.transform.position;
        }
        else if (grab - 2 >= targetGrab)
        {
            if (!justCollided)
            {
                prevGrab[1] = prevGrab[0];
                prevGrab[0] = grab;
            }
            grab   -= 2f;
            prevPos = this.transform.position;
        }
        //this.transform.localScale = tempScale;
        //rb.MovePosition(parent.transform.position + transform.TransformDirection(new Vector3 (0.1f, 0f ,0f)));// change to half scale later
        //Vector3 moveTo = this.transform.TransformPoint(new Vector3(0f,0f,0f));
        //rb.MovePosition(moveTo);// change to half scale later
        if (this.name == "hand 1")
        {
            ConfigurableJoint grabbedJoint = null;
            if (grabbed == GameObject.Find("hand 2").GetComponent <grabberHand>().grabbed&& grabbed != this.gameObject)
            {
                if (grabbed.GetComponent <ConfigurableJoint>() == null || grabbed.GetComponent <ConfigurableJoint>().connectedBody != rb)
                {
                    Debug.Log(grabbed.name);
                    grabbedJoint = grabbed.AddComponent <ConfigurableJoint>();
                    grabbedJoint.connectedBody  = rb;
                    grabbedJoint.xMotion        = ConfigurableJointMotion.Locked;
                    grabbedJoint.yMotion        = ConfigurableJointMotion.Locked;
                    grabbedJoint.zMotion        = ConfigurableJointMotion.Locked;
                    grabbedJoint.angularXMotion = ConfigurableJointMotion.Locked;
                    grabbedJoint.angularYMotion = ConfigurableJointMotion.Locked;
                    grabbedJoint.angularZMotion = ConfigurableJointMotion.Locked;
                }
            }
            else
            {
                if (grabbed.GetComponent <ConfigurableJoint>() != null && grabbed.GetComponent <ConfigurableJoint>().connectedBody == rb)
                {
                    Destroy(grabbed.GetComponent <ConfigurableJoint>());
                    Debug.Log("destroy");
                    //grab = prevGrab[0];
                    targetGrab       = prevGrab[0];
                    grabSlider.value = prevGrab[0];
                }
            }
        }

        if (this.name == "hand 1" && grabbed != GameObject.Find("hand 2").GetComponent <grabberHand>().grabbed)
        {
            if (grabbed.GetComponent <ConfigurableJoint>() != null && grabbed.GetComponent <ConfigurableJoint>().connectedBody == rb)
            {
                Destroy(grabbed.GetComponent <ConfigurableJoint>());
                Debug.Log("destroy");
                //grab = prevGrab[0];
                targetGrab       = prevGrab[0];
                grabSlider.value = prevGrab[0];
            }
        }
        if (waitCount > 200)
        {
            /*rb.MoveRotation(parent.transform.rotation);
             * if (this.name == "hand 1"){
             *      rb.MovePosition(parent.transform.TransformPoint(new Vector3(sizes2.x/2/otherScale, (-sizes2.y/2 - sizes.y/2)*1.1f/otherScale,(-sizes2.z/2 - sizes.z/2)*grab/100f/otherScale)));
             *      //Debug.Log(parent.transform.TransformPoint(new Vector3(sizes2.x/2, (-sizes2.y/2 - sizes.y/2)*1.1f,(-sizes2.z/2 - sizes.z/2)*grab/100f/otherScale)));
             * }
             *
             * else if (this.name == "hand 2"){
             *      rb.MovePosition(parent.transform.TransformPoint(new Vector3(sizes2.x/2/otherScale, (-sizes2.y/2 - sizes.y/2)*1.1f/otherScale, (sizes2.z/2 + sizes.z/2)*grab/100f/otherScale)));
             * }*/
            //cj.targetPosition = Math.Sign(this.transform.localPosition.z)*tempScale*(parent.transform.lossyScale.z)/2;
            if (!justCollided && cj != null)
            {
                cj.autoConfigureConnectedAnchor = false;
                Vector3 tempScale = cj.connectedAnchor;
                if (this.name == "hand 1")
                {
                    tempScale.z        = -grab / 100f * (sizes2.z / 2 + sizes.z / 2) / otherScale * offsets.z;
                    cj.connectedAnchor = tempScale;
                }

                else if (this.name == "hand 2")
                {
                    tempScale.z        = grab / 100f * (sizes2.z / 2 + sizes.z / 2) / otherScale * offsets.z;
                    cj.connectedAnchor = tempScale;
                }
            }
            //if (grab < prevGrab + 5 && prevGrab > prevGrab -5){
            //	cj.zMotion = ConfigurableJointMotion.Limited;
            //}
            //else{
            //cj.zMotion = ConfigurableJointMotion.Locked;
            //cj.connectedBody = null;
            //cj.connectedBody = jointParent.GetComponent<Rigidbody>();
            //}
            moveBy = 1f;
        }


        grabbed      = this.gameObject;
        justCollided = false;
    }
    void Set_ParentArm(string Direction)
    {
        // Create ParentArm GameObject
        GameObject Temp_Object = new GameObject("ParentArm_" + Direction + "_" + (Count_Parent + 1));

        Temp_Object.transform.parent        = Parent_Transform;
        Temp_Object.transform.localPosition = new Vector3(ParentArmPos_X, ParentArmPos_Y, ParentArmPos_Z);
        Temp_Object.transform.localRotation = Quaternion.Euler(0.0f, 0.0f, -90.0f);
        // Mesh
        Temp_Object.AddComponent <MeshRenderer> ();
        MeshFilter Temp_MeshFilter;

        Temp_MeshFilter = Temp_Object.AddComponent <MeshFilter> ();
        if (Direction == "R")
        {
            Temp_MeshFilter.mesh = ParentArm_R_MeshProp.objectReferenceValue as Mesh;
            Temp_Object.GetComponent <Renderer>().material = ParentArm_R_MaterialProp.objectReferenceValue as Material;
        }
        else
        {
            Temp_MeshFilter.mesh = ParentArm_L_MeshProp.objectReferenceValue as Mesh;
            Temp_Object.GetComponent <Renderer>().material = ParentArm_L_MaterialProp.objectReferenceValue as Material;
        }
        // Rigidbody
        Temp_Object.AddComponent <Rigidbody> ();
        Temp_Object.GetComponent <Rigidbody>().mass = ParentArm_MassProp.floatValue;
        // Reinforce SphereCollider
        SphereCollider Temp_SphereCollider;

        Temp_SphereCollider        = Temp_Object.AddComponent <SphereCollider> ();
        Temp_SphereCollider.radius = 0.45f;
        // ConfigurableJoint
        ConfigurableJoint Temp_Joint;

        Temp_Joint = Temp_Object.AddComponent <ConfigurableJoint> ();
        Temp_Joint.connectedBody  = Parent_Transform.parent.gameObject.GetComponent <Rigidbody>();
        Temp_Joint.anchor         = new Vector3(0.0f, ParentArm_Offset_YProp.floatValue, 0.0f);
        Temp_Joint.axis           = Vector3.zero;
        Temp_Joint.secondaryAxis  = Vector3.zero;
        Temp_Joint.xMotion        = ConfigurableJointMotion.Locked;
        Temp_Joint.yMotion        = ConfigurableJointMotion.Limited;
        Temp_Joint.zMotion        = ConfigurableJointMotion.Locked;
        Temp_Joint.angularXMotion = ConfigurableJointMotion.Limited;
        Temp_Joint.angularYMotion = ConfigurableJointMotion.Locked;
        Temp_Joint.angularZMotion = ConfigurableJointMotion.Locked;
        SoftJointLimit Temp_SoftJointLimit = Temp_Joint.linearLimit;          // Set Linear Limit

        Temp_SoftJointLimit.limit    = 0.1f;
        Temp_Joint.linearLimit       = Temp_SoftJointLimit;
        Temp_SoftJointLimit          = Temp_Joint.lowAngularXLimit; // Set Low Angular XLimit
        Temp_SoftJointLimit.limit    = -ParentArm_AngleLimitProp.floatValue;
        Temp_Joint.lowAngularXLimit  = Temp_SoftJointLimit;
        Temp_SoftJointLimit          = Temp_Joint.highAngularXLimit; // Set High Angular XLimit
        Temp_SoftJointLimit.limit    = ParentArm_AngleLimitProp.floatValue;
        Temp_Joint.highAngularXLimit = Temp_SoftJointLimit;
        JointDrive Temp_JointDrive = Temp_Joint.yDrive;          // Set Vertical Spring.

        Temp_JointDrive.mode           = JointDriveMode.Position;
        Temp_JointDrive.positionSpring = SpringProp.floatValue;
        Temp_Joint.yDrive = Temp_JointDrive;
        // Set Layer
        Temp_Object.layer = 10;          // Ignore All
    }
Esempio n. 28
0
		private void INTERNAL_set_highTwistLimit(ref SoftJointLimit value){}
 void Update()
 {
     SoftJointLimit joint = FrontUpperLegs[0].swing2Limit;
 }
Esempio n. 30
0
		private void INTERNAL_set_swing2Limit(ref SoftJointLimit value){}
Esempio n. 31
0
        // 移動や回転制限
        void SetMotionAngularLock(PMDFormat.Joint joint, ConfigurableJoint conf)
        {
            SoftJointLimit jlim;

            // Motionの固定
            if (joint.constrain_pos_1.x == 0f && joint.constrain_pos_2.x == 0f)
            {
                conf.xMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.xMotion = ConfigurableJointMotion.Limited;
            }

            if (joint.constrain_pos_1.y == 0f && joint.constrain_pos_2.y == 0f)
            {
                conf.yMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.yMotion = ConfigurableJointMotion.Limited;
            }

            if (joint.constrain_pos_1.z == 0f && joint.constrain_pos_2.z == 0f)
            {
                conf.zMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.zMotion = ConfigurableJointMotion.Limited;
            }

            // 角度の固定
            if (joint.constrain_rot_1.x == 0f && joint.constrain_rot_2.x == 0f)
            {
                conf.angularXMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.angularXMotion = ConfigurableJointMotion.Limited;
                float          hlim  = Mathf.Max(-joint.constrain_rot_1.x, -joint.constrain_rot_2.x);       //回転方向が逆なので負数
                float          llim  = Mathf.Min(-joint.constrain_rot_1.x, -joint.constrain_rot_2.x);
                SoftJointLimit jhlim = new SoftJointLimit();
                jhlim.limit            = Mathf.Clamp(hlim * Mathf.Rad2Deg, -180.0f, 180.0f);
                conf.highAngularXLimit = jhlim;

                SoftJointLimit jllim = new SoftJointLimit();
                jllim.limit           = Mathf.Clamp(llim * Mathf.Rad2Deg, -180.0f, 180.0f);
                conf.lowAngularXLimit = jllim;
            }

            if (joint.constrain_rot_1.y == 0f && joint.constrain_rot_2.y == 0f)
            {
                conf.angularYMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                // 値がマイナスだとエラーが出るので注意
                conf.angularYMotion = ConfigurableJointMotion.Limited;
                float lim = Mathf.Min(Mathf.Abs(joint.constrain_rot_1.y), Mathf.Abs(joint.constrain_rot_2.y));                //絶対値の小さい方
                jlim               = new SoftJointLimit();
                jlim.limit         = lim * Mathf.Clamp(Mathf.Rad2Deg, 0.0f, 180.0f);
                conf.angularYLimit = jlim;
            }

            if (joint.constrain_rot_1.z == 0f && joint.constrain_rot_2.z == 0f)
            {
                conf.angularZMotion = ConfigurableJointMotion.Locked;
            }
            else
            {
                conf.angularZMotion = ConfigurableJointMotion.Limited;
                float lim = Mathf.Min(Mathf.Abs(-joint.constrain_rot_1.z), Mathf.Abs(-joint.constrain_rot_2.z));                //絶対値の小さい方//回転方向が逆なので負数
                jlim               = new SoftJointLimit();
                jlim.limit         = Mathf.Clamp(lim * Mathf.Rad2Deg, 0.0f, 180.0f);
                conf.angularZLimit = jlim;
            }
        }
Esempio n. 32
0
		private void INTERNAL_set_linearLimit(ref SoftJointLimit value){}
Esempio n. 33
0
    void AddJointPhysicsLengthen(int n)
    {
        joints[n] = new GameObject("Joint_" + (n));
        joints[n].transform.parent = transform;
        joints[n].layer            = 8;
        joints[n].AddComponent <Ignoraa>();
        joints[n].AddComponent <JointBrake>();
        Rigidbody rigid = joints[n].AddComponent <Rigidbody>();

        //rigid.useGravity = false;
        //rigid.mass = 0.01f;
        rigid.angularDrag              = ropeAngDrag;
        rigid.interpolation            = RigidbodyInterpolation.Interpolate;
        rigid.collisionDetectionMode   = CollisionDetectionMode.ContinuousDynamic;
        rigid.maxDepenetrationVelocity = maxDepenetrationVelocity;
        SphereCollider col = joints[n].AddComponent <SphereCollider>();
        CharacterJoint ph  = joints[n].AddComponent <CharacterJoint>();

        ph.breakForce  = breakForce;
        ph.breakTorque = breakTorque;
        ph.autoConfigureConnectedAnchor = autoAnchor;
        ph.enablePreprocessing          = enableProcessing;
        ph.enableProjection             = enableProjection;
        ph.swingAxis          = swingAxis;
        ph.axis               = axis;
        ph.projectionDistance = projectionDistance;
        ph.projectionAngle    = projectionAngle;
        SoftJointLimit       limit_setter = ph.lowTwistLimit;
        SoftJointLimitSpring setti        = ph.swingLimitSpring;
        SoftJointLimit       highTwist    = ph.highTwistLimit;

        highTwist.contactDistance = contactDistance1;
        SoftJointLimit swing1 = ph.swing1Limit;

        swing1.contactDistance = contactDistance3;
        swing1.limit           = swing1Limit;
        SoftJointLimit swing2 = ph.swing2Limit;

        swing2.contactDistance       = contactDistance4;
        swing2.limit                 = swing2Limit;
        ph.swing1Limit               = swing1;
        ph.swing2Limit               = swing2;
        ph.highTwistLimit            = highTwist;
        setti.damper                 = damper;
        setti.spring                 = spring;
        limit_setter.contactDistance = contactDistance2;
        ph.twistLimitSpring          = setti;
        ph.swingLimitSpring          = setti;

        limit_setter.limit = lowTwistLimit;
        ph.lowTwistLimit   = limit_setter;
        limit_setter       = ph.highTwistLimit;
        limit_setter.limit = highTwistLimit;
        ph.highTwistLimit  = limit_setter;
        limit_setter       = ph.swing1Limit;
        limit_setter.limit = swing1Limit;
        ph.swing1Limit     = limit_setter;

        //ph.breakForce = ropeBreakForce; <--------------- TODO

        joints[n].transform.position = segmentPos[n];

        rigid.drag = ropeDrag;
        rigid.mass = ropeMass;
        col.radius = ropeColRadius;

        if (n == 0)
        {
            ph.connectedBody = transform.GetComponent <Rigidbody>();
        }
        else
        {
            ph.connectedBody = joints[n - 1].GetComponent <Rigidbody>();
        }
    }
Esempio n. 34
0
		private void INTERNAL_set_highAngularXLimit(ref SoftJointLimit value){}
Esempio n. 35
0
        public void LoadBoomHead()
        {
            if (savedSectionsLocalPos.Count > 0)
            {
                //Reset section(s) to org pos
                foreach (KeyValuePair <int, SectionInfo> section in sections)
                {
                    section.Value.transform.position = this.part.transform.TransformPoint(section.Value.orgLocalPos);
                }
            }

            KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) Create physical object...");
            boomHeadPhysicModule = this.part.gameObject.GetComponent <KASModulePhysicChild>();
            if (!boomHeadPhysicModule)
            {
                KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - KASModulePhysicChild do not exist, adding it...");
                boomHeadPhysicModule = this.part.gameObject.AddComponent <KASModulePhysicChild>();
            }
            boomHeadPhysicModule.mass      = boomHeadMass;
            boomHeadPhysicModule.physicObj = sections[0].transform.gameObject;
            boomHeadPhysicModule.Start();

            orgBoomHeadMass = this.part.mass;
            float newMass = this.part.mass - boomHeadMass;

            if (newMass > 0)
            {
                this.part.mass = newMass;
            }
            else
            {
                KAS_Shared.DebugWarning("LoadBoomHead(TelescopicArm) - Mass of the boom head is greater than the part !");
            }

            KAS_Shared.DebugLog("LoadRotor - Disable collision...");
            disableSectionCollision();

            KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Create configurable joint...");
            slideJoint = this.part.gameObject.AddComponent <ConfigurableJoint>();
            slideJoint.connectedBody  = sections[0].transform.rigidbody;
            slideJoint.axis           = Vector3.zero;
            slideJoint.secondaryAxis  = Vector3.zero;
            slideJoint.breakForce     = breakForce;
            slideJoint.breakTorque    = breakForce;
            slideJoint.angularXMotion = ConfigurableJointMotion.Locked;
            slideJoint.angularYMotion = ConfigurableJointMotion.Locked;
            slideJoint.angularZMotion = ConfigurableJointMotion.Locked;
            slideJoint.xMotion        = ConfigurableJointMotion.Locked;
            slideJoint.yMotion        = ConfigurableJointMotion.Locked;
            slideJoint.zMotion        = ConfigurableJointMotion.Locked;

            if (direction.x != 0)
            {
                slideJoint.xMotion = ConfigurableJointMotion.Limited;
                driveWay           = direction.x;
                KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Direction set to x axis with driveWay set to : " + driveWay);
            }
            else if (direction.y != 0)
            {
                slideJoint.yMotion = ConfigurableJointMotion.Limited;
                driveWay           = direction.y;
                KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Direction set to y axis with driveWay set to : " + driveWay);
            }
            else if (direction.z != 0)
            {
                slideJoint.zMotion = ConfigurableJointMotion.Limited;
                driveWay           = direction.z;
                KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Direction set to z axis with driveWay set to : " + driveWay);
            }

            JointDrive drv = new JointDrive();

            drv.mode           = JointDriveMode.PositionAndVelocity;
            drv.positionSpring = driveSpring;
            drv.positionDamper = driveDamper;
            drv.maximumForce   = driveForce;
            slideJoint.xDrive  = slideJoint.yDrive = slideJoint.zDrive = drv;

            SoftJointLimit jointLimit = new SoftJointLimit();

            jointLimit.limit       = sectionTotalLenght;
            jointLimit.damper      = 200;
            jointLimit.spring      = 1000;
            jointLimit.bounciness  = 1;
            slideJoint.linearLimit = jointLimit;

            if (savedSectionsLocalPos.Count > 0)
            {
                KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Re-set section position from save");
                float sumLenght = 0;
                foreach (KeyValuePair <int, SectionInfo> section in sections)
                {
                    KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Move section " + section.Key + " to local position : " + section.Value.savedLocalPos);
                    section.Value.transform.position = this.part.transform.TransformPoint(section.Value.savedLocalPos);
                    sumLenght += section.Value.lenght;
                    if (headPos > sumLenght)
                    {
                        KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Parent section " + sections[section.Key + 1].transform.name + " to : " + section.Value.transform.name);
                        sections[section.Key + 1].transform.parent = section.Value.transform;
                    }
                }
            }

            // Get boom head attach nodes
            attachNodes.Clear();
            ConfigNode    node          = KAS_Shared.GetBaseConfigNode(this);
            List <string> attachNodesSt = new List <string>(node.GetValues("attachNode"));

            foreach (String anString in attachNodesSt)
            {
                AttachNode an = this.part.findAttachNode(anString);
                if (an != null)
                {
                    KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Boom head attach node added : " + an.id);
                    attachNodes.Add(an);
                    if (an.attachedPart)
                    {
                        KAS_Shared.DebugLog("LoadBoomHead(TelescopicArm) - Setting boom head joint on : " + an.attachedPart.partInfo.title);
                        KAS_Shared.RemoveFixedJointBetween(this.part, an.attachedPart);
                        KAS_Shared.RemoveHingeJointBetween(this.part, an.attachedPart);
                        FixedJoint fjnt = an.attachedPart.gameObject.AddComponent <FixedJoint>();
                        fjnt.connectedBody = sections[0].transform.rigidbody;
                        fixedJnts.Add(fjnt);
                    }
                }
            }
            SetTargetPos(targetPos);
            boomHeadLoaded = true;
        }
Esempio n. 36
0
		private void INTERNAL_set_angularZLimit(ref SoftJointLimit value){}
/////////////This is the algorythm that picks up the carried object
    void PickUpSwitchStatement()
    {
        //notHolding       //if not holding, the statement is ignored
        //checkBoxPresence,//checks that it is alright to pick something up
        //automateLift,    // lifts the object into position
        //attachJoint,     // joins the object to Jenny
        //pickUpInterupted,//drops the object, halts the process if interupted
        //pickUpComplete,  // move object around with Jenny
        //puttingDown      //puts down the object, sets state to not holding

        switch (pickUpState)
        {
        case (PickUpStates.notHolding):
            break;            //this is the default state of the pick up loop

        //In the check box line we see if there is a box to pick up,
        //if the is remove control and set the pickupstate to picking up something
        case (PickUpStates.checkBoxPresence):
            directionOfCharacter = GetDirection();
            liftStartTime        = Time.time;
            pickUpRayStart       = new Vector2(jennyTransform.position.x,
                                               jennyTransform.position.y - 0.5f * jennyTransform.localScale.y);
            hit2 = Physics2D.Raycast(pickUpRayStart,
                                     new Vector2(directionOfCharacter.x, 0.0f)
                                     , 4.5f, 1 << 8);
            //layer of pickuppable stuff is 8.
            if (hit2.collider != null)
            {
                //Debug.Log ("The hit object is called"+ hit2.transform.name);
//				Physics2D.Raycast (pickUpRayStart, new Vector2(directionOfCharacter.x,0.0f)  ,  4.5f , layerMaskOfHit)
//				&& hit2.collider.CompareTag ("PickUp")



                jennyShoot.heldObject = hit2.transform;
                jennyShoot.shotState  = JennyShoot.ShotState.startHolding;
                //jennyShoot.canShoot = false;



                //There is a box in front of the character it is picked up prefferentially
//				typeOfPickUp = "fromSide";
                automatedPickUpComplete = false;
                //Remove control from the character Controller during the animation
                canControl = false;
                //the transform of the pick up box;
                itemCurrentlyHeld = hit2.transform;
                //Gravity removed so it doesn't mess with the physics of the jumping
                itemCurrentlyHeld.GetComponent <Rigidbody2D>().gravityScale = 0.0f;
                itemCurrentlyHeld.GetComponent <Rigidbody2D>().isKinematic  = false;
                //assign the mass of the objec for reference
                massOfObjInitial = itemCurrentlyHeld.GetComponent <Rigidbody2D>().mass;



                //this still doesn't work if the two colliders are touching sweeptest doesn't work here


                ///////////////////////////////
                ///////////////////////////////
                //There is more than one type of lorentz contraction
                //it depends on what kind of box we are picking up.
                ///////////////////////////////
                ///////////////////////////////
                lorentzContraction =
                    itemCurrentlyHeld.GetComponent("LorentzContraction")
                    as LorentzContraction;
                //This allows a c
                lorentzContraction.IsBeingPickedUp = true;

                //We need to set the carried objects scale back to it's original settings
                itemCurrentlyHeld.localScale = new Vector3(lorentzContraction.xScale0,
                                                           lorentzContraction.yScale0, lorentzContraction.zScale0);

                //We need to remove the rigidbody x constraint
                //CONSTRAINT MUST BE DONE WITH A JOINT
                //hit2.transform.rigidbody2D.constraints = RigidbodyConstraints.FreezePositionZ
                //	|RigidbodyConstraints.FreezeRotation;
                lorentzContraction.xMotionStatic = false;



                //The initial position is needed to do the lift
                initialXposition = itemCurrentlyHeld.position.x;
                //initialHeightOfCarried = itemCurrentlyHeld.position.y;
                //liftStartTime = Time.time;


                //the goal height will be how far above Jenny the block must be (shouldn't calculate more than once.
                goalHeight     = 0.5f * jennyTransform.localScale.y + 7.0f + 0.5f * itemCurrentlyHeld.localScale.y;
                riseSpeed      = goalHeight / riseTime;
                slideOverSpeed = jennyTransform.localScale.x / riseTime;

                //make the object lighter for transport and lift
                itemCurrentlyHeld.GetComponent <Rigidbody2D>().mass = massOfObjCarried;

                //This moves the switch statement to the next part of the loop
                pickUpState = PickUpStates.automateLift;
                goto case PickUpStates.automateLift;
            }
            else
            {
                //If there is no box to pick up, leave the loop
                pickUpState = PickUpStates.notHolding;
                break;
            }

        case (PickUpStates.automateLift):

            //interupt the lift if it takes too long
            if (Time.time > liftStartTime + maxLiftDuration)
            {
                pickUpState = PickUpStates.pickUpInterupted;
                goto case PickUpStates.pickUpInterupted;
            }


            if (!automatedPickUpComplete)
            {
                if (itemCurrentlyHeld == null)
                {
                    pickUpState = PickUpStates.pickUpInterupted;
                    goto case PickUpStates.pickUpInterupted;
                }
                else
                {
                    automatedPickUpComplete = pickUpAutomation();                     //typeOfPickUp);
                    break;
                }
            }
            else
            {
                pickUpState = PickUpStates.attachJoint;
                goto case PickUpStates.attachJoint;
            }

        case (PickUpStates.attachJoint):

            //interupt the lift if it takes too long
            if (Time.time > liftStartTime + maxLiftDuration)
            {
                pickUpState = PickUpStates.pickUpInterupted;
                goto case PickUpStates.pickUpInterupted;
            }

            //Initialize the joint.
            holdingJoint = jennyTransform.gameObject.AddComponent <SliderJoint2D> ();
            //The carried objects can only pivot around the z axis
            //holdingJoint.axis = new Vector2 (0.0f, 1.0f);
            //The carried object will be a short distance from
            holdingJoint.connectedBody = itemCurrentlyHeld.GetComponent <Rigidbody2D>();

            holdingJoint.angle     = 0.0f;
            holdingJoint.anchor    = new Vector2(0.0f, goalHeight / jennyTransform.localScale.y);
            holdingJoint.useLimits = true;
            //holdingJoint2.xMotion = ConfigurableJointMotion.Limited;
            //Define DeltaXShift to be used by the carried object's script LorentzContractions
            //DeltaXShift = (itemCurrentlyHeld.position.x - jennyTransform.position.x);


            lorentzContraction.IsBeingHeld = true;

            holdingSomething = true;



            //We need to remove the rigidbody x constraint
            //CONSTRAINT MUST BE DONE WITH A JOINT
            //hit2.transform.rigidbody.constraints = RigidbodyConstraints.FreezePositionZ
            //	|RigidbodyConstraints.FreezeRotation;
            lorentzContraction.xMotionStatic = false;



            //directionAtPickUp=Mathf.Sign(movement.direction.x);
            //The maximum range of xcoordinate is set up by playing
            //with the joint limits
            SoftJointLimit holdingJointLimits = new SoftJointLimit();

            //holdingJointLimits.spring = 0.0f;
            //holdingJointLimits.damper = 0.0f;
            holdingJointLimits.bounciness = 0.0f;

            holdingJointLimits.limit = lorentzContraction.xScale0;


            //holdingJointLimits.limit = lorentzContraction.xScale0;
            //holdingJoint2.linearLimit = holdingJointLimits;

            //The holding joint's target position is defaulted to zero
            //holdingJoint2.targetPosition = new Vector3 (0.0f, 0.0f, 0.0f);

            //The carried object is driven with this force
            JointDrive holdingJointDrive = new JointDrive();
            holdingJointDrive.mode           = JointDriveMode.Position;
            holdingJointDrive.positionSpring = 500.0f;
            holdingJointDrive.positionDamper = 0.0f;
            holdingJointDrive.maximumForce   = Mathf.Infinity;
            //holdingJoint2.yDrive = holdingJointDrive;


            //Return control to the character Controller
            canControl = true;


            //Define DeltaXShift to have correct lorentz contractions
            //see the update loop.
            //DeltaXShift = (itemCurrentlyHeld.position.x - jennyTransform.position.x);


            pickUpState = PickUpStates.pickUpComplete;
            break;

        case (PickUpStates.pickUpInterupted):
            //If the lift is interupted in any way this gets called
            //May need a different one if it is mid-top-lift

            if (itemCurrentlyHeld != null)
            {
                //return mass to original mass just in case;
                itemCurrentlyHeld.GetComponent <Rigidbody2D>().mass = massOfObjInitial;
                //I need to turn gravity back on for the carried object
                itemCurrentlyHeld.GetComponent <Rigidbody2D>().gravityScale = GameControl.control.gravity;
            }


            //Return control to the character Controller
            canControl = true;

            //JENNY CAN SHOOT AGAIN
            jennyShoot.shotState = JennyShoot.ShotState.turnOnShoot;
            //jennyShoot.canShoot = true;
            jennyShoot.heldObject = null;


            pickUpState = PickUpStates.notHolding;
            break;

        case (PickUpStates.pickUpComplete):


            //The carried box needs to stay centered even under lorentz contraction
            directionOfCharacter = GetDirection();
            gammaX = lorentzContractionForJenny.gammaX;
            //hold

            //holdingJoint2.targetPosition = new Vector3 (0.0f,
            //                                            DeltaXShift * directionOfCharacter.x * (1 - 1 / gammaX),
            //                                            0.0f);
            break;



        case (PickUpStates.puttingDown):
            lorentzContraction.IsBeingHeld = false;

            //Gravity removed so it doesn't mess with the physics of the jumping
            itemCurrentlyHeld.GetComponent <Rigidbody2D>().gravityScale = GameControl.control.gravity;

            Destroy(holdingJoint);
            holdingSomething = false;
            canControl       = true;


            //SET MOVEMENT SPEED TO ZERO WHEN SOMETHING LET GO
            movement.targetSpeed = 0.0f;
            movement.gammaX      = 1f;
            lorentzContractionForJenny.gammaX = 1.0f;


            //I need picked up object to have the same velocity as the Jenny when she let go.

            if (gammaX < 1.5f)
            {
                //If jenny is moving slowly, actively push the block off so it doesn't land on her if possibel
                lorentzContraction.XVelocityGoal = GetVxTargetFromGammaX(1.5f)               //lorentzContractionForJenny.GetXVelocity VxNew
                                                   * movement.direction.x;
            }
            else
            {
                lorentzContraction.XVelocityGoal = lorentzContractionForJenny.VxNew
                                                   * movement.direction.x;
            }

            //bumb the carried object a little so it moves away from Jenny.
            itemCurrentlyHeld.transform.GetComponent <Rigidbody2D>().velocity += new Vector2(0.0f, 10.0f);

            //set the objects mass back to original
            itemCurrentlyHeld.GetComponent <Rigidbody2D>().mass = massOfObjInitial;


            //JENNY CAN SHOOT AGAIN
            jennyShoot.shotState = JennyShoot.ShotState.turnOnShoot;
            //jennyShoot.canShoot = true;
            jennyShoot.heldObject = null;



            //When the object is released the state goes back to not holding
            pickUpState = PickUpStates.notHolding;
            break;

        case (PickUpStates.objectDestroyed):
            //has the object been destroyed while being carried?

            lorentzContraction.IsBeingHeld = false;


            Destroy(holdingJoint);
            holdingSomething = false;
            canControl       = true;


            //JENNY CAN SHOOT AGAIN
            jennyShoot.shotState = JennyShoot.ShotState.turnOnShoot;
            //jennyShoot.canShoot = true;
            jennyShoot.heldObject = null;



            //When the object is released the state goes back to not holding
            pickUpState = PickUpStates.notHolding;
            break;
        }
    }
    // Token: 0x060001F1 RID: 497 RVA: 0x00009088 File Offset: 0x00007288
    public override bool PeiceInspectorGUI()
    {
        bool   flag    = base.PeiceInspectorGUI();
        string peiceID = base.peiceID;

        if (global::AuthorShared.StringField("Title", ref peiceID, new GUILayoutOption[0]))
        {
            base.peiceID = peiceID;
            flag         = true;
        }
        global::AuthorShared.EnumField("Kind", this.kind, new GUILayoutOption[0]);
        global::AuthorShared.PrefixLabel("Self");
        if (GUILayout.Button(global::AuthorShared.ObjectContent <global::AuthorChHit>(this.self, typeof(global::AuthorChHit)), new GUILayoutOption[0]))
        {
            global::AuthorShared.PingObject(this.self);
        }
        flag |= global::AuthorShared.PeiceField <global::AuthorChHit>("Connected", this, ref this.connect, typeof(global::AuthorChHit), GUI.skin.button, new GUILayoutOption[0]);
        flag |= global::AuthorShared.Toggle("Reverse Link", ref this.reverseLink, new GUILayoutOption[0]);
        flag |= global::AuthorShared.Vector3Field("Anchor", ref this.anchor, new GUILayoutOption[0]);
        flag |= global::AuthorShared.Vector3Field("Axis", ref this.axis, new GUILayoutOption[0]);
        global::AuthorChJoint.Kind kind = this.kind;
        if (kind != global::AuthorChJoint.Kind.Hinge)
        {
            if (kind == global::AuthorChJoint.Kind.Character)
            {
                flag |= global::AuthorShared.Vector3Field("Swing Axis", ref this.swingAxis, new GUILayoutOption[0]);
                SoftJointLimit softJointLimit = this.lowTwist;
                if (global::AuthorChJoint.Field("Low Twist", ref softJointLimit, ref this.twistOffset))
                {
                    flag          = true;
                    this.lowTwist = softJointLimit;
                }
                softJointLimit = this.highTwist;
                if (global::AuthorChJoint.Field("High Twist", ref softJointLimit, ref this.twistOffset))
                {
                    flag           = true;
                    this.highTwist = softJointLimit;
                }
                softJointLimit = this.swing1;
                if (global::AuthorChJoint.Field("Swing 1", ref softJointLimit, ref this.swingOffset1))
                {
                    flag        = true;
                    this.swing1 = softJointLimit;
                }
                softJointLimit = this.swing2;
                if (global::AuthorChJoint.Field("Swing 2", ref softJointLimit, ref this.swingOffset2))
                {
                    flag        = true;
                    this.swing2 = softJointLimit;
                }
            }
        }
        else
        {
            JointLimits limit = this.limit;
            if (global::AuthorChJoint.Field("Limits", ref limit, ref this.useLimit, ref this.limitOffset))
            {
                flag       = true;
                this.limit = limit;
            }
        }
        flag |= global::AuthorShared.FloatField("Break Force", ref this.breakForce, new GUILayoutOption[0]);
        return(flag | global::AuthorShared.FloatField("Break Torque", ref this.breakTorque, new GUILayoutOption[0]));
    }
Esempio n. 39
0
            public ConfigurableJoint CreateLink()
            {
                if (this.joint != null)
                {
                    log.warning("This link already has a joint object.");
                    return(this.joint);
                }
                if (_isTrackingDockingPorts)
                {
                    this.joint = new ConfigurableJoint();
                    return(this.joint);
                }

                try
                {
                    AttachNode parent     = this.nodes[0];
                    AttachNode child      = this.nodes[1];
                    Part       parentPart = this.parts[0];
                    Part       childPart  = this.parts[1];

                    log.debug("Creating joint between " + parentPart.name + " and " + childPart.name + ".");

                    if (parentPart.Rigidbody == null)
                    {
                        log.error("parentPart body is null :o");
                    }
                    if (childPart.Rigidbody == null)
                    {
                        log.error("childPart body is null :o");
                    }

                    ConfigurableJoint newJoint;

                    newJoint = childPart.gameObject.AddComponent <ConfigurableJoint>();
                    newJoint.connectedBody   = parentPart.Rigidbody;
                    newJoint.anchor          = Vector3.zero;        // There's probably a better anchor point, like the attachNode...
                    newJoint.connectedAnchor = Vector3.zero;

                    newJoint.autoConfigureConnectedAnchor = false;  // Probably don't need.
                    newJoint.axis            = Vector3.up;
                    newJoint.secondaryAxis   = Vector3.left;
                    newJoint.enableCollision = false;               // Probably don't need.

                    newJoint.breakForce  = float.PositiveInfinity;  //Math.Min(parentPart.breakingForce, childPart.breakingForce);
                    newJoint.breakTorque = float.PositiveInfinity;  //Math.Min(parentPart.breakingTorque, childPart.breakingTorque);

                    newJoint.angularXMotion = ConfigurableJointMotion.Limited;
                    newJoint.angularYMotion = ConfigurableJointMotion.Limited;
                    newJoint.angularZMotion = ConfigurableJointMotion.Limited;

                    JointDrive linearDrive = new JointDrive();
                    linearDrive.maximumForce   = 1E20f;
                    linearDrive.positionDamper = 0;
                    linearDrive.positionSpring = 1E20f;
                    newJoint.xDrive            = linearDrive;
                    newJoint.yDrive            = linearDrive;
                    newJoint.zDrive            = linearDrive;

                    newJoint.projectionDistance = 0.1f;
                    newJoint.projectionAngle    = 180;
                    newJoint.projectionMode     = JointProjectionMode.None;

                    newJoint.rotationDriveMode     = RotationDriveMode.XYAndZ;
                    newJoint.swapBodies            = false;
                    newJoint.targetAngularVelocity = Vector3.zero;
                    newJoint.targetPosition        = Vector3.zero;
                    newJoint.targetVelocity        = Vector3.zero;
                    newJoint.targetRotation        = new Quaternion(0, 0, 0, 1);

                    JointDrive angularDrive = new JointDrive();
                    angularDrive.maximumForce   = 1E20f;
                    angularDrive.positionSpring = 60000;
                    angularDrive.positionDamper = 0;
                    newJoint.angularXDrive      = angularDrive;
                    newJoint.angularYZDrive     = angularDrive;

                    SoftJointLimitSpring zeroSpring = new SoftJointLimitSpring();
                    zeroSpring.spring             = 0;
                    zeroSpring.damper             = 0;
                    newJoint.angularXLimitSpring  = zeroSpring;
                    newJoint.angularYZLimitSpring = zeroSpring;

                    SoftJointLimit angleSoftLimit = new SoftJointLimit();
                    angleSoftLimit.bounciness      = 0;
                    angleSoftLimit.contactDistance = 0;
                    angleSoftLimit.limit           = 177;
                    newJoint.angularYLimit         = angleSoftLimit;
                    newJoint.angularZLimit         = angleSoftLimit;
                    newJoint.highAngularXLimit     = angleSoftLimit;
                    newJoint.lowAngularXLimit      = angleSoftLimit;

                    this.joint = newJoint;
                }
                catch (Exception ex)
                {
                    log.error("Could not create physical joint: " + ex);
                }
                this.SetNodes();

                ConnectedLivingSpacesCompatibility.RequestAddConnection(this.parts[0], this.parts[1]);
                ReCouplerUtils.onReCouplerJointFormed.Fire(new GameEvents.HostedFromToAction <Vessel, Part>(parts[0].vessel, parts[0], parts[1]));
                return(this.joint);
            }
Esempio n. 40
0
    private bool DoTransformHandles(ref AuthorChHit.Rep self, ref AuthorChHit.Rep connect)
    {
        if (!self.valid)
        {
            return(false);
        }
        Vector3   vector3   = self.Flip(this.anchor);
        Vector3   vector31  = self.AxisFlip(this.axis);
        Vector3   vector32  = self.AxisFlip(this.swingAxis);
        Matrix4x4 matrix4x4 = AuthorShared.Scene.matrix;

        if (connect.valid)
        {
            AuthorShared.Scene.matrix = connect.bone.localToWorldMatrix;
            Color color = AuthorShared.Scene.color;
            AuthorShared.Scene.color = color * new Color(1f, 1f, 1f, 0.4f);
            Vector3 vector33 = connect.bone.InverseTransformPoint(self.bone.position);
            if (vector33 != Vector3.zero)
            {
                AuthorShared.Scene.DrawBone(Vector3.zero, Quaternion.LookRotation(vector33), vector33.magnitude, 0.02f, new Vector3(0.05f, 0.05f, 0.5f));
            }
            AuthorShared.Scene.color = color;
        }
        AuthorShared.Scene.matrix = self.bone.localToWorldMatrix;
        bool flag = false;

        if (AuthorShared.Scene.PivotDrag(ref vector3, ref vector31))
        {
            flag        = true;
            this.anchor = self.Flip(vector3);
            this.axis   = self.AxisFlip(vector31);
        }
        AuthorChJoint.Kind kind = this.kind;
        if (kind != AuthorChJoint.Kind.Hinge)
        {
            if (kind == AuthorChJoint.Kind.Character)
            {
                Color color1 = AuthorShared.Scene.color;
                AuthorShared.Scene.color = color1 * AuthorChJoint.twistColor;
                SoftJointLimit softJointLimit  = this.lowTwist;
                SoftJointLimit softJointLimit1 = this.highTwist;
                if (AuthorShared.Scene.LimitDrag(vector3, vector31, ref this.twistOffset, ref softJointLimit, ref softJointLimit1))
                {
                    flag           = true;
                    this.lowTwist  = softJointLimit;
                    this.highTwist = softJointLimit1;
                }
                AuthorShared.Scene.color = color1 * AuthorChJoint.swing1Color;
                softJointLimit           = this.swing1;
                if (AuthorShared.Scene.LimitDrag(vector3, vector32, ref this.swingOffset1, ref softJointLimit))
                {
                    flag        = true;
                    this.swing1 = softJointLimit;
                }
                AuthorShared.Scene.color = color1 * AuthorChJoint.swing2Color;
                softJointLimit           = this.swing2;
                if (AuthorShared.Scene.LimitDrag(vector3, Vector3.Cross(vector32, vector31), ref this.swingOffset2, ref softJointLimit))
                {
                    flag        = true;
                    this.swing2 = softJointLimit;
                }
                AuthorShared.Scene.color = color1;
            }
        }
        else if (this.useLimit)
        {
            JointLimits jointLimit = this.limit;
            if (AuthorShared.Scene.LimitDrag(vector3, vector31, ref this.limitOffset, ref jointLimit))
            {
                flag       = true;
                this.limit = jointLimit;
            }
        }
        AuthorShared.Scene.matrix = matrix4x4;
        return(flag);
    }
Esempio n. 41
0
            // 移動や回転制限
            void SetMotionAngularLock(PMDFormat.Joint joint, ConfigurableJoint conf)
            {
                SoftJointLimit jlim;

                // Motionの固定
                if (joint.constrain_pos_1.x == 0f && joint.constrain_pos_2.x == 0f)
                    conf.xMotion = ConfigurableJointMotion.Locked;
                else
                    conf.xMotion = ConfigurableJointMotion.Limited;

                if (joint.constrain_pos_1.y == 0f && joint.constrain_pos_2.y == 0f)
                    conf.yMotion = ConfigurableJointMotion.Locked;
                else
                    conf.yMotion = ConfigurableJointMotion.Limited;

                if (joint.constrain_pos_1.z == 0f && joint.constrain_pos_2.z == 0f)
                    conf.zMotion = ConfigurableJointMotion.Locked;
                else
                    conf.zMotion = ConfigurableJointMotion.Limited;

                // 角度の固定
                if (joint.constrain_rot_1.x == 0f && joint.constrain_rot_2.x == 0f)
                    conf.angularXMotion = ConfigurableJointMotion.Locked;
                else
                {
                    conf.angularXMotion = ConfigurableJointMotion.Limited;
                    float hlim = joint.constrain_rot_1.x > joint.constrain_rot_2.x ? joint.constrain_rot_1.x : joint.constrain_rot_2.x;
                    float llim = joint.constrain_rot_1.x < joint.constrain_rot_2.x ? joint.constrain_rot_1.x : joint.constrain_rot_2.x;
                    SoftJointLimit jhlim = new SoftJointLimit();
                    jhlim.limit = hlim * Mathf.Rad2Deg;
                    conf.highAngularXLimit = jhlim;

                    SoftJointLimit jllim = new SoftJointLimit();
                    jllim.limit = -llim * Mathf.Rad2Deg;
                    conf.lowAngularXLimit = jllim;
                }

                if (joint.constrain_rot_1.y == 0f && joint.constrain_rot_2.y == 0f)
                    conf.angularYMotion = ConfigurableJointMotion.Locked;
                else
                {
                    // 値がマイナスだとエラーが出るので注意
                    conf.angularYMotion = ConfigurableJointMotion.Limited;
                    float lim = joint.constrain_rot_1.y > joint.constrain_rot_2.y ? joint.constrain_rot_1.y : joint.constrain_rot_2.y;
                    jlim = new SoftJointLimit();
                    jlim.limit = lim * Mathf.Rad2Deg;
                    conf.angularYLimit = jlim;
                }

                if (joint.constrain_rot_1.z == 0f && joint.constrain_rot_2.z == 0f)
                    conf.angularZMotion = ConfigurableJointMotion.Locked;
                else
                {
                    conf.angularZMotion = ConfigurableJointMotion.Limited;
                    float lim = joint.constrain_rot_1.z > joint.constrain_rot_2.z ? joint.constrain_rot_1.z : joint.constrain_rot_2.z;
                    jlim = new SoftJointLimit();
                    jlim.limit = lim * Mathf.Rad2Deg;
                    conf.angularZLimit = jlim;
                }
            }