示例#1
0
        public static Tuple<HingeJoint, AngleJoint> ConnectWith(this BaseModelBody parentBody, BaseModelBody childBody, Vector2D hingeLocation)
        {
            var hinge = new HingeJoint(parentBody, childBody, hingeLocation, new Lifespan())
            {
                DistanceTolerance = 50,
                Softness = 10000.1
            };
            var angle = new AngleJoint(parentBody, childBody, new Lifespan()) { Softness = -0.00000001, BiasFactor = 0.3};

            return new Tuple<HingeJoint, AngleJoint>(hinge, angle);
        }
        protected override void Open()
        {
            dispose += DemoHelper.BasicDemoSetup(DemoInfo);


            Scene.Engine.AddLogic(new GravityField(new Vector2D(0, 1000), new Lifespan()));

            List<Body> chain = DemoHelper.AddChain(DemoInfo, new Vector2D(400, 50), 100, 30, 200, 20, 800);
            Vector2D point = new Vector2D(300, 50);

            Body Anchor = DemoHelper.AddCircle(DemoInfo, 30, 18, Scalar.PositiveInfinity, new ALVector2D(0, point));
            Anchor.IgnoresGravity = true;
            HingeJoint joint = new HingeJoint(chain[0], Anchor, point, new Lifespan());
            joint.DistanceTolerance = 10;
            Scene.Engine.AddJoint(joint);
        }
        protected override void Open()
        {
            dispose += DemoHelper.BasicDemoSetup(DemoInfo);
            dispose += DemoHelper.CreateTank(DemoInfo, new Vector2D(50, 0));


            Scene.Engine.AddLogic(new GravityField(new Vector2D(0, 1000), new Lifespan()));

            IShape shape = ShapeFactory.CreateSprite(Cache<SurfacePolygons>.GetItem("block.png"), 3, 7, 4);
            DemoHelper.AddGrid(
                DemoInfo, shape, 20,
                new BoundingRectangle(400, 200, 500, 510),
                50, 2);


            Scalar boxlength = 50;
            Scalar spacing = 4;
            Scalar anchorLenght = 30;
            Scalar anchorGap = (boxlength / 2) + spacing + (anchorLenght / 2);
            List<Body> chain = DemoHelper.AddChain(DemoInfo, new Vector2D(200, 500), boxlength, 20, 200, spacing, 600);

            Vector2D point2 = new Vector2D(chain[chain.Count - 1].State.Position.Linear.X + anchorGap, 500);
            Body end2 = DemoHelper.AddCircle(DemoInfo, anchorLenght / 2, 14, Scalar.PositiveInfinity, new ALVector2D(0, point2));
            end2.IgnoresGravity = true;
            HingeJoint joint2 = new HingeJoint(chain[chain.Count - 1], end2, point2, new Lifespan());
            joint2.DistanceTolerance = 10;
            Scene.Engine.AddJoint(joint2);

            Vector2D point1 = new Vector2D(chain[0].State.Position.Linear.X - anchorGap, 500);
            Body end1 = DemoHelper.AddCircle(DemoInfo, anchorLenght / 2, 14, Scalar.PositiveInfinity, new ALVector2D(0, point1));
            end1.IgnoresGravity = true;
            HingeJoint joint1 = new HingeJoint(chain[0], end1, point1, new Lifespan());
            joint1.DistanceTolerance = 10;
            Scene.Engine.AddJoint(joint1);
            end2.State.Position.Linear.X -= 10;
            end1.State.Position.Linear.X += 10;
            end2.ApplyPosition();
            end1.ApplyPosition();


        }
示例#4
0
 void OnDrawGizmosSelected()
 { // Visualize the angles settings.
     for (int i = 0; i < transform.childCount; i++)
     {
         Transform childTransform = transform.GetChild(i);
         if (childTransform.gameObject.layer == Layer_Settings_CS.Reinforce_Layer)
         { // Suspension Arm.
             HingeJoint joint         = childTransform.GetComponent <HingeJoint>();
             Transform  bodyTransform = joint.connectedBody.transform;
             Vector3    anchorPos     = bodyTransform.position + (bodyTransform.right * joint.connectedAnchor.x) + (bodyTransform.up * joint.connectedAnchor.y) + (bodyTransform.forward * joint.connectedAnchor.z);
             float      currentAng    = joint.limits.max - Sus_Forward_Limit;
             Vector3    tempPos;
             tempPos.x = 0.0f;
             // Limits Min
             tempPos.y    = Mathf.Sin(Mathf.Deg2Rad * (joint.limits.min - currentAng)) * Sus_Length;
             tempPos.z    = -Mathf.Cos(Mathf.Deg2Rad * (joint.limits.min - currentAng)) * Sus_Length;
             Gizmos.color = Color.green;
             Gizmos.DrawLine(anchorPos, anchorPos + (bodyTransform.up * tempPos.y) + (bodyTransform.forward * tempPos.z));
             // Limits Max
             tempPos.y    = Mathf.Sin(Mathf.Deg2Rad * (joint.limits.max - currentAng)) * Sus_Length;
             tempPos.z    = -Mathf.Cos(Mathf.Deg2Rad * (joint.limits.max - currentAng)) * Sus_Length;
             Gizmos.color = Color.green;
             Gizmos.DrawLine(anchorPos, anchorPos + (bodyTransform.up * tempPos.y) + (bodyTransform.forward * tempPos.z));
             // Target
             tempPos.y    = Mathf.Sin(Mathf.Deg2Rad * (joint.spring.targetPosition - currentAng)) * Sus_Length;
             tempPos.z    = -Mathf.Cos(Mathf.Deg2Rad * (joint.spring.targetPosition - currentAng)) * Sus_Length;
             Gizmos.color = Color.red;
             Gizmos.DrawLine(anchorPos, anchorPos + (bodyTransform.up * tempPos.y) + (bodyTransform.forward * tempPos.z));
             // Current
             currentAng   = childTransform.localEulerAngles.y;
             tempPos.y    = Mathf.Sin(Mathf.Deg2Rad * -currentAng) * Sus_Length;
             tempPos.z    = -Mathf.Cos(Mathf.Deg2Rad * -currentAng) * Sus_Length;
             Gizmos.color = Color.yellow;
             Gizmos.DrawLine(anchorPos, anchorPos + (bodyTransform.up * tempPos.y) + (bodyTransform.forward * tempPos.z));
         }
     }
 }
示例#5
0
    protected void RagdollOn(Transform t)
    {
        Rigidbody rb = t.gameObject.AddComponent <Rigidbody>();

        //rb.constraints = RigidbodyConstraints.FreezePosition;
        rb.useGravity  = true;
        rb.drag        = 1;
        rb.angularDrag = 1;
        rb.angularDrag = 1;
        //rb.maxAngularVelocity = 5;
        rb.mass = 1;
        Rigidbody parentRb;

        if ((parentRb = t.parent.GetComponent <Rigidbody>()) != null)
        {
            HingeJoint j = t.gameObject.AddComponent <HingeJoint>();
            j.autoConfigureConnectedAnchor = true;
            j.connectedBody = parentRb;
            //j.enableCollision = true;
            //j.connectedAnchor = Vector3.Scale(t.localPosition, t.lossyScale);
            j.axis = new Vector3(1, 1, 1);
        }
        if (t.GetComponent <Collider>() != null)
        {
            return;
        }
        CapsuleCollider bc = t.gameObject.AddComponent <CapsuleCollider>();

        bc.radius    = 0.15f;
        bc.height    = 0.6f;// Vector3.Scale(t.localPosition, t.lossyScale).magnitude;
        bc.direction = 0;
        bc.center    = new Vector3(-bc.height / 2, 0, 0);
        for (int i = 0; i < t.childCount; ++i)
        {
            RagdollOn(t.GetChild(i));
        }
    }
示例#6
0
 void Start()
 {
     targetGO = GameObject.Find("Wizard").transform;
     target   = FindGranchild(targetGO);
     hj       = gameObject.AddComponent <HingeJoint>();
     if (connectedBody == null)
     {
         connectedBody = transform.parent.GetComponent <Rigidbody>();
         CharacterJoint cj = GetComponent <CharacterJoint>();
         if (cj)
         {
             connectedBody = cj.connectedBody;
             //maxTwist = -cj.highTwistLimit.limit;
             //minTwist = -cj.lowTwistLimit.limit;
             if (!ignoreCharacterJointAxis)
             {
                 x = cj.axis.x != 0;
                 y = cj.axis.y != 0;
                 z = cj.axis.z != 0;
             }
             Destroy(cj);
         }
     }
     hj.connectedBody = connectedBody;
     hj.axis          = new Vector3(x ? 1 : 0, y ? 1 : 0, z ? 1 : 0);
     hj.useLimits     = true;
     hj.useSpring     = true;
     hj.limits        = new JointLimits
     {
         max = maxTwist,
         min = minTwist
     };
     hj.spring = new JointSpring
     {
         spring = springAmount
     };
 }
示例#7
0
    void GroundCheck(Vector3 pos, GameObject pivot)
    {
        Vector3    GroundPosL = new Vector3(0, 20, -15);
        Vector3    GroundPosR = new Vector3(0, 20, 15);
        GameObject ground     = null;

        if (pos.y == GroundPosL.y && pos.z == GroundPosL.z)
        {
            ground = GameObject.Find("Ground L");
        }
        else if (pos.y == GroundPosR.y && pos.z == GroundPosR.z)
        {
            ground = GameObject.Find("Ground R");
        }
        if ((pos.y == GroundPosL.y && pos.z == GroundPosL.z) || (pos.y == GroundPosR.y && pos.z == GroundPosR.z)) //check if connected 2 ground
        {
            //FixedJoint fj = pivot.AddComponent<FixedJoint>();
            //fj.connectedBody = ground.GetComponent<Rigidbody>();

            HingeJoint hj = pivot.AddComponent <HingeJoint>();
            hj.connectedBody = ground.GetComponent <Rigidbody>();
            hj.axis          = new Vector3(0, 1, 0);
        }
    }
示例#8
0
        void Start()
        {
            MakeMaterial();
            _pinballManager = FindObjectOfType <PinballManager>();
            _rb             = GetComponent <Rigidbody>();
            _hingeJoint     = GetComponent <HingeJoint>();

            // Trying to improve physics by overriding the defaults.
            _rb.maxAngularVelocity       = 0;
            _rb.maxDepenetrationVelocity = _rb.maxDepenetrationVelocity * 5;
            _rb.solverIterations         = 30;
            _rb.solverVelocityIterations = 5;

            _jointSpring = _hingeJoint.spring;
            _jointMotor  = _hingeJoint.motor;

            _hingeJoint.useMotor  = false;
            _hingeJoint.useSpring = true;

            _jointMotor.force          = _pinballManager._flipperMotorForce;
            _jointMotor.targetVelocity = _pinballManager._flipperMotorTargetVelocity;

            _jointSpring.spring = _pinballManager._springForce;
        }
示例#9
0
文件: Rope.cs 项目: lenix2/VRProject
    internal void Start()
    {
        if (!isServer)
        {
            Debug.Log("DESTROY_ROPE");
            Destroy(this);
        }
        Vector3 savePos = this.gameObject.transform.position;

        float ropePartLength = ropeLength / ropeCount;
        int   childCount     = this.transform.childCount;
        int   zCount         = 0;

        ropePart.transform.localScale = new Vector3(ropeWidth, ropePartLength, ropeWidth);

        for (int i = 1; i <= ropeCount; i++)
        {
            GameObject tmpRope = GameObject.Instantiate(ropePart, new Vector3(ropePart.transform.position.x, ropePart.transform.position.y + (-2f * i * ropePartLength), ropePart.transform.position.z), ropePart.transform.localRotation, this.gameObject.transform) as GameObject;
            if (i == ropeCount)
            {
                GameObject tmpHook = GameObject.Instantiate(ropeHook, new Vector3(ropePart.transform.position.x, ropePart.transform.position.y + (-2f * i * ropePartLength), ropePart.transform.position.z), ropePart.transform.localRotation, this.gameObject.transform) as GameObject;
            }
        }

        for (int i = 1; i <= ropeCount + 2; i++)
        {
            Transform t = this.transform.GetChild(i);

            t.gameObject.AddComponent <HingeJoint> ();
            HingeJoint hinge = t.gameObject.GetComponent <HingeJoint> ();
            hinge.connectedBody = i == 0 ? this.RBody : this.transform.GetChild(i - 1).GetComponent <Rigidbody> ();

            hinge.useSpring       = true;
            hinge.enableCollision = true;
        }
    }
    //public override void OnInspectorGUI()

    public override void OnInspectorGUI()
    {
        //DrawDefaultInspector();

        HingeJoint myTarget = (HingeJoint)target;

        myTarget.connectedBody = (Rigidbody)EditorGUILayout.ObjectField("Connected Body", myTarget.connectedBody, typeof(Rigidbody), true);

        myTarget.anchor = EditorGUILayout.Vector3Field("Anchor", myTarget.anchor);

        myTarget.axis = EditorGUILayout.Vector3Field("Axis", myTarget.axis);

        myTarget.autoConfigureConnectedAnchor = EditorGUILayout.Toggle("Auto Configure Connected Anchor", myTarget.autoConfigureConnectedAnchor);

        //using(var group = new EditorGUILayout.FadeGroupScope(Convert.ToSingle(myTarget.autoConfigureConnectedAnchor)))
        //  if (myTarget.autoConfigureConnectedAnchor == false)
        myTarget.connectedAnchor = EditorGUILayout.Vector3Field("Connected Anchor", myTarget.connectedAnchor);

        //myTarget.breakForce = EditorGUILayout.FloatField("Break Force", myTarget.breakForce);
        //myTarget.breakTorque = EditorGUILayout.FloatField("Break Torque", myTarget.breakForce);

        //myTarget.enableCollision = EditorGUILayout.Toggle("Enable Collision", myTarget.enableCollision);
        //myTarget.enablePreprocessing = EditorGUILayout.Toggle("Enable Preprocessing", myTarget.enablePreprocessing);
    }
示例#11
0
    void OnCollisionEnter(Collision col)
    {
        HingeJoint hj = gameObject.GetComponent <HingeJoint>();

        if (hj != null)
        {
            return;
        }

        if (col.collider.tag == "Grabbable")
        {
            if (tin.TouchActive)
            {
                hj = gameObject.AddComponent <HingeJoint>();
                hj.connectedBody = col.rigidbody;
                hj.anchor        = transform.InverseTransformPoint(col.contacts[0].point);
                hj.axis          = Vector3.zero;
            }
        }
        else if (col.collider.tag == "SolidGround")
        {
            groundGuarantee = true;
        }
    }
    void Start()
    {
        if (minXAngle != 0)
        {
            offset = minXAngle * -1;
        }
        methodGetLocalEulerAngles = typeof(Transform).GetMethod("GetLocalEulerAngles", BindingFlags.Instance | BindingFlags.NonPublic);
        propertyRotationOrder     = typeof(Transform).GetProperty("rotationOrder", BindingFlags.Instance | BindingFlags.NonPublic);

        _interact = GetComponent <InteractionBehaviour>();
        _render   = GetComponent <Renderer>();
        _hinge    = GetComponent <HingeJoint>();

        mat = new MaterialPropertyBlock();
        mat.SetColor("_Color", Color.red);

        JointMotor motor = _hinge.motor;

        motor.targetVelocity = 0;
        motor.force          = 1000;
        motor.freeSpin       = false;
        _hinge.motor         = motor;
        _hinge.useMotor      = true;
    }
示例#13
0
    private void MakeJoint()
    {
        if (parent == Enums.Direction.None)
        {
            return;
        }

        joint = gameObject.AddComponent <HingeJoint>();
        switch (details.motion)
        {
        case Enums.Motion.Rotational:
            MakeRotationalJoint();
            break;

        case Enums.Motion.Linear:
            MakeLinearJoint();
            break;

        case Enums.Motion.None:
        default:
            MakeBasicJoint();
            break;
        }
    }
    void OnCollisionEnter(Collision col)
    {
        Debug.Log("Collided");
        Debug.Log(inAir);
        distanceBetween = Vector3.Distance(transform.position, player.GetComponent <Transform>().position);
        //GetComponent<Rigidbody>().isKinematic = true;
        //if (inAir != false)
        //{
        GetComponent <Rigidbody>().mass     = 100;
        GetComponent <Rigidbody>().velocity = Vector3.zero;
        //    Debug.Log("set");
        //    inAir = false;
        //grabHinge = gameObject.AddComponent<HingeJoint>();
        //Debug.Log(col.rigidbody);
        //grabHinge.axis = Vector3.back;
        //grabHinge.connectedBody = col.rigidbody;
        //ContactPoint contact = col.contacts[0];

        //grabHinge.anchor = Vector3.zero;

        playerHinge               = player.AddComponent <HingeJoint>();
        playerHinge.anchor        = transform.position;
        playerHinge.axis          = Vector3.back;
        playerHinge.connectedBody = gameObject.GetComponent <Rigidbody>();

        //Debug.Log(transform.localPosition);

        //swingJoint = player.AddComponent<SpringJoint>();
        //swingJoint.connectedBody = GetComponent<Rigidbody>();

        //swingJoint.anchor = transform.localPosition;
        //swingJoint.maxDistance = 0;
        //swingJoint.
        //Tstops the hook once it collides with something, and creates a HingeJoint to the object it collided with.
        // }
    }
示例#15
0
    internal void Start()
    {
        this.gameObject.AddComponent <Rigidbody>();
        this.RBody             = this.gameObject.GetComponent <Rigidbody>();
        this.RBody.isKinematic = true;

        int childCount = this.transform.childCount;

        for (int i = 0; i < childCount; i++)
        {
            Transform t = this.transform.GetChild(i);

            t.gameObject.AddComponent <HingeJoint>();

            HingeJoint hinge = t.gameObject.GetComponent <HingeJoint>();

            hinge.connectedBody =
                i == 0 ? this.RBody :
                this.transform.GetChild(i - 1).GetComponent <Rigidbody>();

            hinge.useSpring       = true;
            hinge.enableCollision = true;
        }
    }
    void Move()
    {
        GameObject trolley = scrGameManager.Instance.Trolley;
        HingeJoint joint   = trolley.hingeJoint;
        JointMotor motor   = trolley.hingeJoint.motor;

        // Rotate to face the new direction.
        if (targetDirection.magnitude != 0)
        {
            rigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(targetDirection), turnSpeed * Time.fixedDeltaTime));
            rigidbody.MovePosition(transform.position + targetDirection * moveSpeed * targetDirection.magnitude * Time.fixedDeltaTime);


            // Add influence to trolley.
            motor.force          = Vector2.Angle(new Vector2(transform.forward.x, transform.forward.z), new Vector2(trolley.transform.forward.x, trolley.transform.forward.z)) * 10;
            motor.targetVelocity = Vector2.Dot(new Vector2(transform.forward.x, transform.forward.z), new Vector2(trolley.transform.right.x, trolley.transform.right.z)) * motor.force;
            joint.motor          = motor;
        }
        else
        {
            motor.targetVelocity *= 0.95f;
            joint.motor           = motor;
        }
    }
示例#17
0
        public override void OnEnter()
        {
            var go = gameObject.OwnerOption == OwnerDefaultOption.UseOwner ? Owner : gameObject.GameObject.Value;

            if (go == null)
            {
                LogWarning("Missing gameObject");
                return;
            }

            _joint = go.GetComponent <HingeJoint>();
            if (_joint == null)
            {
                LogWarning("Missing HingeJoint");
                return;
            }

            DoSetProperties();

            if (!everyFrame)
            {
                Finish();
            }
        }
示例#18
0
    public void OnTriggerEnter(Collider other)
    {
        if (state != State.Landing)
        {
            return;
        }

        if (other != collToLandOn)
        {
            return;
        }

        stateTimer = Random.Range(3.0f, 12.0f);
        state      = State.Stationary;

        //body.isKinematic = true;

        var rig = other.transform.GetComponent <Rigidbody>();

        if (rig)
        {
            rig.AddForceAtPosition(body.velocity * 0.75f, transform.position, ForceMode.Impulse);
            //add joint 420 boii
            m_Hinge           = this.gameObject.AddComponent <HingeJoint>();
            m_Hinge.useLimits = true;
            var limits = m_Hinge.limits;
            limits.max     = 0;
            limits.min     = 0;
            m_Hinge.limits = limits;
            m_Hinge.autoConfigureConnectedAnchor = true;
            m_Hinge.connectedBody = rig;
        }
        GetComponent <Collider>().enabled = false;

        body.velocity = Vector3.zero;
    }
示例#19
0
        private void Initialize(Direction hingeAxis)
        {
            inchBody            = PartTransform.gameObject.AddComponent <Rigidbody>();
            joint               = PartTransform.gameObject.AddComponent <HingeJoint>();
            joint.connectedBody = attachedToBody;
            if (hingeAxis == Direction.X)
            {
                joint.axis = Vector3.right;
            }
            else if (hingeAxis == Direction.Y)
            {
                joint.axis = Vector3.up;
            }
            if (hingeAxis == Direction.Z)
            {
                joint.axis = Vector3.forward;
            }
            JointLimits limits = joint.limits;

            limits.min      = -61.897f;
            joint.limits    = limits;
            joint.useLimits = true;
            joint.autoConfigureConnectedAnchor = true;
        }
    /// <summary> The start method adds pointers to existing rigidbody objects and joints in the scene. Additionally, the start positions of all rigid bodies are taken,
    /// which will be used to reset objects at the beginning of each episode
    /// </summary>
    void Start()
    {
        //Apply constraints to shoulder
        shoulder = GameObject.Find("Shoulder").GetComponent <Rigidbody>();

        //shoulderjoint = shoulder.GetComponent<CharacterJoint>();
        upperarm             = GameObject.Find("UpperArm").GetComponent <Rigidbody>();
        forearm              = GameObject.Find("Forearm").GetComponent <Rigidbody>();
        shoulder.constraints = RigidbodyConstraints.FreezePosition;
        elbow      = GameObject.Find("Elbow").GetComponent <Rigidbody>();
        elbowjoint = elbow.GetComponent <HingeJoint>();
        hand       = GameObject.Find("Hand").GetComponent <Rigidbody>();

        //store current eblow motor
        elbowmotor                = elbowjoint.motor;
        elbowmotor.force          = 100;
        elbowmotor.targetVelocity = 90;
        target = GameObject.Find("Target").GetComponent <Rigidbody>();

        // create a motor object for moving the elbow joint
        var motor = elbowjoint.motor;

        motor.force          = 100;
        motor.targetVelocity = 0;
        motor.freeSpin       = false;
        elbowjoint.motor     = motor;
        elbowjoint.useMotor  = true;


        //store positions of each component for when episode resets
        shoulder_pos = shoulder.transform.position;
        upperarm_pos = upperarm.transform.position;
        elbow_pos    = elbow.transform.position;
        forearm_pos  = forearm.transform.position;
        hand_pos     = hand.transform.position;
    }
示例#21
0
    public void CreateChains()
    {
        HingeJoint prev = null;

        for (int i = 0; i < chainCount + 1; i++)
        {
            GameObject obj = Instantiate(inst, transform);

            Vector3 scale = obj.transform.localScale;
            scale.y = chainHeight;

            obj.transform.localScale = scale;
            obj.transform.position   = startPos.position + (transform.up * (chainHeight * 2) * i) + transform.up * chainHeight;

            if (prev)
            {
                Rigidbody self = obj.GetComponent <Rigidbody>();

                prev.connectedBody = self;
            }

            prev = obj.GetComponent <HingeJoint>();
        }
    }
示例#22
0
    // Start is called before the first frame update
    void Awake()
    {
        switch (type_Joint)
        {
        default:
            break;

        case Type_Joint.Rotation:
            this.hinge_joint          = this.gameObject.AddComponent <HingeJoint>();
            hinge_joint.connectedBody = Connected_Body.GetComponent <Rigidbody>();
            hinge_joint.anchor        = this.Anchor;
            hinge_joint.axis          = this.Axis;

            if (!use_automatic_parent_anchor)
            {
                hinge_joint.autoConfigureConnectedAnchor = false;
                hinge_joint.connectedAnchor = this.Connected_Anchor;
            }

            this.GetComponent <Rigidbody>().useGravity  = false;
            this.GetComponent <Rigidbody>().isKinematic = true;
            break;
        }
    }
示例#23
0
        private void InitDoor()
        {
            GameObject actualDoor = GetDoor();

            VRTK_SharedMethods.CreateColliders(actualDoor);

            doorRigidbody = actualDoor.GetComponent <Rigidbody>();
            if (doorRigidbody == null)
            {
                doorRigidbody             = actualDoor.AddComponent <Rigidbody>();
                doorRigidbody.angularDrag = releasedFriction;
            }
            doorRigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; // otherwise door will not react to fast moving controller
            doorRigidbody.isKinematic            = false;                                    // in case nested door as already created this

            doorHinge = actualDoor.GetComponent <HingeJoint>();
            if (doorHinge == null)
            {
                doorHinge        = actualDoor.AddComponent <HingeJoint>();
                doorHingeCreated = true;
            }
            doorHinge.connectedBody = frameRigidbody;

            doorSnapForce = actualDoor.GetComponent <ConstantForce>();
            if (doorSnapForce == null)
            {
                doorSnapForce         = actualDoor.AddComponent <ConstantForce>();
                doorSnapForce.enabled = false;
                doorSnapForceCreated  = true;
            }

            if (!handleInteractableOnly)
            {
                CreateInteractableObject(actualDoor);
            }
        }
示例#24
0
       /* public static List<Body> AddSpringChain(DemoOpenInfo info, Vector2D position, Scalar boxLenght, Scalar boxWidth, Scalar boxMass, Scalar spacing, Scalar length)
        {
            List<Body> bodies = new List<Body>();
            Body last = null;
            for (Scalar x = 0; x < length; x += boxLenght + spacing, position.X += boxLenght + spacing)
            {
                Body current = AddRectangle(info, boxWidth, boxLenght, boxMass, new ALVector2D(0, position));
                bodies.Add(current);
                if (last != null)
                {

                    SpringJoint joint = new SpringJoint(last, Vector2D.Zero, current, Vector2D.Zero, 100, 100, new Lifespan());
                    info.Scene.Engine.AddJoint(joint);
                }
                last = current;
            }
            return bodies;
        }*/
        public static List<Body> AddRagDoll(DemoOpenInfo info, Vector2D location)
        {
            List<Body> result = new List<Body>();
            Scalar mass = 10;
            Body head = AddCircle(info, 12, 9, mass, new ALVector2D(0, location + new Vector2D(0, 0)));

            Scalar Ld2 = 50 / 2;
            Scalar Wd2 = 25 / 2;
            Vector2D[] vertexes = new Vector2D[]
            {
                new Vector2D(Wd2, Ld2),
                new Vector2D(5, Ld2+7),
                new Vector2D(-5, Ld2+7),
                new Vector2D(-Wd2, Ld2),
                new Vector2D(-Wd2, 0),
                new Vector2D(-(Wd2+4), -Ld2/2+6),
                new Vector2D(-Wd2+2, -Ld2),
                new Vector2D(0, -Ld2),
                new Vector2D(Wd2-2, -Ld2),
                new Vector2D(Wd2+4, -Ld2/2+6),
                new Vector2D(Wd2, 0),
            };

            IShape shape = ShapeFactory.CreateColoredPolygon(vertexes, 5);

            Body torso = AddShape(info, shape, mass * 4, new ALVector2D(0, location + new Vector2D(0, 40)));

            Body ltarm = AddRectangle(info, 10, 30, mass, new ALVector2D(0, location + new Vector2D(-30, 20)));
            Body lbarm = AddRectangle(info, 10, 30, mass, new ALVector2D(0, location + new Vector2D(-65, 20)));

            Body rtarm = AddRectangle(info, 10, 30, mass, new ALVector2D(0, location + new Vector2D(30, 20)));
            Body rbarm = AddRectangle(info, 10, 30, mass, new ALVector2D(0, location + new Vector2D(65, 20)));

            Body ltleg = AddRectangle(info, 40, 15, mass * 2, new ALVector2D(.06f, location + new Vector2D(-10, 95)));
            Body lbleg = AddRectangle(info, 40, 15, mass * 2, new ALVector2D(0, location + new Vector2D(-11, 140)));

            Body rtleg = AddRectangle(info, 40, 15, mass * 1.5f, new ALVector2D(-.06f, location + new Vector2D(10, 95)));
            Body rbleg = AddRectangle(info, 40, 15, mass * 1.5f, new ALVector2D(0, location + new Vector2D(11, 140)));

            result.Add(head);
            result.Add(torso);

            result.Add(ltarm);
            result.Add(lbarm);

            result.Add(rtarm);
            result.Add(rbarm);

            result.Add(ltleg);
            result.Add(lbleg);

            result.Add(rtleg);
            result.Add(rbleg);

            HingeJoint neck = new HingeJoint(head, torso, location + new Vector2D(0, 15), new Lifespan());

            HingeJoint lshoulder = new HingeJoint(ltarm, torso, location + new Vector2D(-18, 20), new Lifespan());
            HingeJoint lelbow = new HingeJoint(ltarm, lbarm, location + new Vector2D(-47, 20), new Lifespan());
            HingeJoint rshoulder = new HingeJoint(rtarm, torso, location + new Vector2D(18, 20), new Lifespan());
            HingeJoint relbow = new HingeJoint(rtarm, rbarm, location + new Vector2D(47, 20), new Lifespan());

            HingeJoint lhip = new HingeJoint(ltleg, torso, location + new Vector2D(-8, 72), new Lifespan());
            HingeJoint lknee = new HingeJoint(ltleg, lbleg, location + new Vector2D(-11, 115), new Lifespan());
            HingeJoint rhip = new HingeJoint(rtleg, torso, location + new Vector2D(8, 72), new Lifespan());
            HingeJoint rknee = new HingeJoint(rtleg, rbleg, location + new Vector2D(11, 115), new Lifespan());
            List<Joint> joints = new List<Joint>();
            joints.Add(neck);
            joints.Add(lelbow);
            joints.Add(rshoulder);

            joints.Add(relbow);
            joints.Add(lshoulder);

            joints.Add(lhip);
            joints.Add(lknee);

            joints.Add(rhip);
            joints.Add(rknee);
            foreach (HingeJoint joint in joints)
            {
                joint.DistanceTolerance = 10;
            }
            info.Scene.Engine.AddJointRange(joints);

            return result;
        }
示例#25
0
 public static List<Body> AddChain(DemoOpenInfo info, Vector2D position, Scalar boxLenght, Scalar boxWidth, Scalar boxMass, Scalar spacing, Scalar length)
 {
     List<Body> bodies = new List<Body>();
     Body last = null;
     for (Scalar x = 0; x < length; x += boxLenght + spacing, position.X += boxLenght + spacing)
     {
         Body current = AddRectangle(info, boxWidth, boxLenght, boxMass, new ALVector2D(0, position));
         bodies.Add(current);
         if (last != null)
         {
             Vector2D anchor = (current.State.Position.Linear + last.State.Position.Linear) * .5f;
             HingeJoint joint = new HingeJoint(last, current, anchor, new Lifespan());
             joint.DistanceTolerance = 10;
             info.Scene.Engine.AddJoint(joint);
         }
         last = current;
     }
     return bodies;
 }
示例#26
0
 // Use this for initialization
 void Start()
 {
     this.myHingeJoint = GetComponent <HingeJoint>();
     //フリッパーの傾きを設定
     SetAngle(this.defaultAngle);
 }
    void Move(HingeJoint joint, float ang, float speed)
    /// <summary>
    /// This class moves a single joint to the passed angle
    /// at a specified speed. The angles are defined in the
    /// same way as in the Nao interface. Speed will also be,
    /// but currently is not.
    /// <\summary>
    {
        /// direction sets motion to be clockwise or anti
        float direction = 1;

        /// Some angles have to be changed because of how
        /// Nao defines its angles
        /// Also, set the speed to be in degrees per second
        if (joint == rightShoulder)
        {
            ang   += 40;
            speed *= 246;
        }
        else if (joint == rightElbow)
        {
            ang   *= -1;
            ang    = 180 - ang;
            speed *= 246;
        }
        else if (joint == rightHip)
        {
            ang    = 180 + ang;
            speed *= 378;
        }
        else if (joint == rightAnkle)
        {
            ang   *= -1;
            ang    = 90 - ang;
            speed *= 378;
        }
        else if (joint == rightKnee)
        {
            ang   += 90;
            speed *= 378;
        }
        else if (joint == Neck)
        {
            ang   *= -1;
            ang   += 90;
            speed *= 246;
        }
        else
        {
            speed *= 378;
        }
        for (int i = 0; i < 6; i++)
        /// Set the angle in the list allAngles to the correct limit angle
        {
            if (joint == allJoints[i])
            {
                allAngles[i] = ang;
            }
        }
        /// Turn off joint limits temporarily
        joint.useLimits = false;
        /// Define a motor for the joint
        JointMotor motor = joint.motor;

        if (ang < joint.angle + 90)
        /// Determine direction of rotation
        {
            direction = -1;
        }
        /// Set the motor velocity, and switch the motor on
        motor.targetVelocity = speed * direction;
        joint.motor          = motor;
        joint.useMotor       = true;
    }
示例#28
0
    private float flickAngle   = -20; //Fripperが動いた時の位置の設定



    void Start()
    {
        myHingeJoint = GetComponent <HingeJoint> (); //myHingeJointにオブジェクトのHingejointを代入
        SetAngle(defaultAngle);                      //通常位置の設定
    }
示例#29
0
        private void AddChainCommandExecute(object parameter)
        {
            Will.Instance.Purge();
            Will.Instance.RunPauseWilling(false);

            var startPoint = new Vector2D(300, 800);
            double angle = MathHelper.ToRadians(15.0f);
            double boxlength = 50;
            double spacing = 2;
            double anchorLength = 30;
            double anchorGap = (boxlength / 2) + spacing + (anchorLength / 2);

            var chainId = Guid.NewGuid();

            var chain = WillHelper.BuildChain(startPoint, boxlength, 3, 1200, spacing, 600, chainId);

            var point2 = new Vector2D(chain[chain.Count - 1].State.Position.Linear.X + anchorGap, startPoint.Y);
            var end2 = WillHelper.AddCircle(anchorLength / 2, 6, double.PositiveInfinity, new ALVector2D(0, point2), chainId);
            end2.IgnoresGravity = true;

            var joint2 = new HingeJoint(chain[chain.Count - 1], end2, point2, new Lifespan()) {DistanceTolerance = 20};
            var joint21 = new AngleJoint(chain[chain.Count - 1], end2, new Lifespan()) { Angle = angle };

            var point1 = new Vector2D(chain[0].State.Position.Linear.X - anchorGap, startPoint.Y);
            var end1 = WillHelper.AddCircle(anchorLength / 2, 6, double.PositiveInfinity, new ALVector2D(0, point1), chainId);

            chain.Add(end1);
            chain.Add(end2);

            end1.IgnoresGravity = true;
            var joint1 = new HingeJoint(chain[0], end1, point1, new Lifespan()) {DistanceTolerance = 20};
            var joint11 = new AngleJoint(end1, chain[0], new Lifespan()) { Angle = angle };

            Will.Instance.AddJoint(joint1);Will.Instance.AddJoint(joint11);
            Will.Instance.AddJoint(joint2);Will.Instance.AddJoint(joint21);

            Representation.Instance.RegisterModel(chainId, chain);

            Will.Instance.RunPauseWilling(true);
        }
示例#30
0
 // Start is called before the first frame update
 void Start()
 {
     hinge = GetComponent <HingeJoint>();
 }
示例#31
0
        static public void ApplyAction(MujocoJoint mJoint, float?target = null)
        {
            HingeJoint        hingeJoint        = mJoint.Joint as HingeJoint;
            ConfigurableJoint configurableJoint = mJoint.Joint as ConfigurableJoint;

            if (configurableJoint != null)
            {
                if (!target.HasValue) // handle random
                {
                    target = Random.value * 2 - 1;
                }
                target = Mathf.Clamp(target.Value, -3f, 3f);
                var t = configurableJoint.targetAngularVelocity;
                t.x = target.Value * _velocityScaler;
                configurableJoint.targetAngularVelocity = t;
                var angX = configurableJoint.angularXDrive;
                angX.positionSpring = 1f;
                var scale = mJoint.MaximumForce * Mathf.Pow(Mathf.Abs(target.Value), 3);
                angX.positionDamper             = Mathf.Max(1f, scale);
                angX.maximumForce               = Mathf.Max(1f, scale);
                configurableJoint.angularXDrive = angX;
                return;
            }
            else if (hingeJoint == null)
            {
                return;
            }
            if (hingeJoint.useSpring)
            {
                var ctrlRangeMin = -1f;
                var ctrlRangeMax = 1f;
                // var ctrlRangeMin = 0f;
                // var ctrlRangeMax = 1f;
                var inputScale = ctrlRangeMax - ctrlRangeMin;
                if (!target.HasValue) // handle random
                {
                    target = ctrlRangeMin + (Random.value * inputScale);
                }
                var inputTarget = Mathf.Clamp(target.Value, ctrlRangeMin, ctrlRangeMax);
                if (ctrlRangeMin < 0)
                {
                    inputTarget = Mathf.Abs(ctrlRangeMin) + inputTarget;
                }
                else
                {
                    inputTarget = inputTarget - Mathf.Abs(ctrlRangeMin);
                }
                inputTarget /= inputScale;
                JointSpring js;
                js = hingeJoint.spring;
                var min          = hingeJoint.limits.min;
                var max          = hingeJoint.limits.max;
                var outputScale  = max - min;
                var outputTarget = min + (inputTarget * outputScale);
                js.targetPosition = outputTarget;
                hingeJoint.spring = js;
            }
            else if (hingeJoint.useMotor)
            {
                if (!target.HasValue) // handle random
                {
                    target = Random.value * 2 - 1;
                }

                target = Mathf.Clamp(target.Value, -1f, 1f);
                // target = Mathf.Clamp(target.Value, 0f, 1f);
                // target *= 2;
                // target -= 1f;

                JointMotor jm;
                jm = hingeJoint.motor;
                jm.targetVelocity = target.Value * _velocityScaler;
                hingeJoint.motor  = jm;
            }
        }
示例#32
0
        private void AddCore(Guid geneApplicationId, BaseGeneViewModel gene)
        {
            var core = (CoreGeneViewModel)gene;
            var model = core.GetModelDuplicate();
            model.Id = geneApplicationId;

            var coreBody = WillHelper.CreateCoreBody(model, geneApplicationId);

            var nodes = WillHelper.BuildNodeSlots(coreBody, geneApplicationId);
            coreBody.Children = nodes;
            var corePos = coreBody.State.Position;

            var joints = new List<Joint>();
            foreach (var node in nodes)
            {
                var hinge = new HingeJoint(coreBody, node, (2* node.State.Position.Linear + 8 * corePos.Linear) * 0.1f, new Lifespan())
                {
                    DistanceTolerance = 10,
                    Softness = 100.0
                };
                var angle = new AngleJoint(coreBody, node, new Lifespan()) { Softness = 0.0001, BiasFactor = 0.2f };

                joints.Add(hinge);
                joints.Add(angle);
            }

            Will.Instance.AddModelBodies(new List<BaseModelBody>{ coreBody }.Concat(nodes).ToList());
            Will.Instance.AddJoints(joints);
        }
示例#33
0
        protected override bool DetectSetup()
        {
            // detect axis
            doorHinge = GetDoor().GetComponent <HingeJoint>();
            if (doorHinge && !doorHingeCreated)
            {
                direction = Direction.autodetect;
            }
            finalDirection = (direction == Direction.autodetect) ? DetectDirection() : direction;
            if (finalDirection == Direction.autodetect)
            {
                return(false);
            }
            if (doorHinge && !doorHingeCreated)
            {
                // if there is a hinge joint already it overrides axis selection
                direction = finalDirection;
            }

            // detect opening direction
            Bounds doorBounds = VRTK_SharedMethods.GetBounds(GetDoor().transform, transform);

            if (doorHinge == null || doorHingeCreated)
            {
                if (handles)
                {
                    // determin sub-direction depending on handle location
                    Bounds handleBounds = VRTK_SharedMethods.GetBounds(handles.transform, transform);
                    switch (finalDirection)
                    {
                    case Direction.x:
                        if ((handleBounds.center.z + handleBounds.extents.z) > (doorBounds.center.z + doorBounds.extents.z) || (handleBounds.center.z - handleBounds.extents.z) < (doorBounds.center.z - doorBounds.extents.z))
                        {
                            subDirection       = (handleBounds.center.y > doorBounds.center.y) ? -1 : 1;
                            secondaryDirection = Vector3.up;
                        }
                        else
                        {
                            subDirection       = (handleBounds.center.z > doorBounds.center.z) ? -1 : 1;
                            secondaryDirection = Vector3.forward;
                        }
                        break;

                    case Direction.y:
                        if ((handleBounds.center.z + handleBounds.extents.z) > (doorBounds.center.z + doorBounds.extents.z) || (handleBounds.center.z - handleBounds.extents.z) < (doorBounds.center.z - doorBounds.extents.z))
                        {
                            subDirection       = (handleBounds.center.x > doorBounds.center.x) ? -1 : 1;
                            secondaryDirection = Vector3.right;
                        }
                        else
                        {
                            subDirection       = (handleBounds.center.z > doorBounds.center.z) ? -1 : 1;
                            secondaryDirection = Vector3.forward;
                        }
                        break;

                    case Direction.z:
                        if ((handleBounds.center.x + handleBounds.extents.x) > (doorBounds.center.x + doorBounds.extents.x) || (handleBounds.center.x - handleBounds.extents.x) < (doorBounds.center.x - doorBounds.extents.x))
                        {
                            subDirection       = (handleBounds.center.y > doorBounds.center.y) ? -1 : 1;
                            secondaryDirection = Vector3.up;
                        }
                        else
                        {
                            subDirection       = (handleBounds.center.x > doorBounds.center.x) ? -1 : 1;
                            secondaryDirection = Vector3.right;
                        }
                        break;
                    }
                }
                else
                {
                    switch (finalDirection)
                    {
                    case Direction.x:
                        secondaryDirection = (doorBounds.extents.y > doorBounds.extents.z) ? Vector3.up : Vector3.forward;
                        break;

                    case Direction.y:
                        secondaryDirection = (doorBounds.extents.x > doorBounds.extents.z) ? Vector3.right : Vector3.forward;
                        break;

                    case Direction.z:
                        secondaryDirection = (doorBounds.extents.y > doorBounds.extents.x) ? Vector3.up : Vector3.right;
                        break;
                    }
                    // TODO: derive how to detect -1
                    subDirection = 1;
                }
            }
            else
            {
                // calculate directions from existing anchor
                Vector3 existingAnchorDirection = doorBounds.center - doorHinge.connectedAnchor;
                if (existingAnchorDirection.x != 0)
                {
                    secondaryDirection = Vector3.right;
                    subDirection       = existingAnchorDirection.x <= 0 ? 1 : -1;
                }
                else if (existingAnchorDirection.y != 0)
                {
                    secondaryDirection = Vector3.up;
                    subDirection       = existingAnchorDirection.y <= 0 ? 1 : -1;
                }
                else if (existingAnchorDirection.z != 0)
                {
                    secondaryDirection = Vector3.forward;
                    subDirection       = existingAnchorDirection.z <= 0 ? 1 : -1;
                }
            }

            if (doorHingeCreated)
            {
                float extents = 0;
                if (secondaryDirection == Vector3.right)
                {
                    extents = doorBounds.extents.x / GetDoor().transform.lossyScale.x;
                }
                else if (secondaryDirection == Vector3.up)
                {
                    extents = doorBounds.extents.y / GetDoor().transform.lossyScale.y;
                }
                else
                {
                    extents = doorBounds.extents.z / GetDoor().transform.lossyScale.z;
                }

                doorHinge.anchor = secondaryDirection * subDirection * extents;
                doorHinge.axis   = Direction2Axis(finalDirection);
            }
            if (doorHinge)
            {
                doorHinge.useLimits       = true;
                doorHinge.enableCollision = true;

                JointLimits limits = doorHinge.limits;
                limits.min        = openInward ? -maxAngle : 0;
                limits.max        = openOutward ? maxAngle : 0;
                limits.bounciness = 0;
                doorHinge.limits  = limits;
            }
            if (doorSnapForceCreated)
            {
                float forceToApply = (-5f * GetDirectionFromJoint());
                doorSnapForce.relativeForce = GetThirdDirection(doorHinge.axis, secondaryDirection) * (subDirection * forceToApply);
            }

            return(true);
        }
示例#34
0
文件: Demo.cs 项目: bsvercl/physics2d
        void CreateAvatar()
        {
            Lifespan avatarLifespan = new Lifespan();

            Sprite sprite = GetSprite("tank.png");
            Vector2D[][] polygons = sprite.Polygons;
            MultiPolygonShape shape = new MultiPolygonShape(polygons, 4);
            shape.Tag = sprite;

            ObjectIgnorer ignorer = new ObjectIgnorer();
            Body a = new Body(new PhysicsState(new ALVector2D(0, 0, 0)),
                shape,
                300,//new MassInfo(40, Scalar.PositiveInfinity),
                coefficients.Duplicate(),
                avatarLifespan);
            a.Updated += new EventHandler<UpdatedEventArgs>(avatar_Updated);
            avatarBodies = new List<Body>();
            avatarOffsets = new List<Vector2D>();
            avatarJoints = new List<Joint>();
            avatarBodies.Add(a);
            a.CollisionIgnorer = ignorer;




            Scalar wheelSize = 18;
            Scalar wheelSpacing = -9;
            Scalar lenghtPercent = .84f;
            Matrix2x3 ident = Matrix2x3.Identity;
            BoundingRectangle rect;
            shape.CalcBoundingRectangle(ref ident, out rect);
            Scalar y = (rect.Max.Y +4)  ;
            Body lastWheel = null ;
            BoundingPolygon polygon = new BoundingPolygon(polygons[0]);

            Ray ray2 = new Ray(new Vector2D(rect.Max.X, y), -Vector2D.YAxis);
            Scalar y3 = y - polygon.Intersects(ray2);
            avatarBarrelOffset = new Vector2D(rect.Max.X, y3);
            
            for (Scalar x = rect.Min.X + wheelSize ; x < (rect.Max.X - wheelSize ) * lenghtPercent; x += (wheelSize*2 + wheelSpacing))
            {

                Ray ray = new Ray(new Vector2D(x, y), -Vector2D.YAxis);
                Scalar y2 = y-  polygon.Intersects(ray);



                Vector2D offset = new Vector2D(x, y2);

                Body wheel = new Body(
                    new PhysicsState(new ALVector2D(0, offset)),
                    new CircleShape(wheelSize, 30),
                    10,
                    new Coefficients(0,3),//  coefficients.Duplicate(),
                    avatarLifespan);
                HingeJoint joint = new HingeJoint(a, wheel, offset, avatarLifespan);
                joint.Softness = .1f;
                wheel.CollisionIgnorer = ignorer;

                if (lastWheel != null)
                {
                    AngleJoint joint2 = new AngleJoint(lastWheel, wheel, avatarLifespan);
                    avatarJoints.Add(joint2);
                }

                avatarJoints.Add(joint);
                avatarOffsets.Add(offset);
                avatarBodies.Add(wheel);
                lastWheel = wheel;
            }
        }
示例#35
0
 void Start()
 {
     joint = GetComponent <HingeJoint>();
     motor = joint.motor;
 }
示例#36
0
        public static DisposeCallback CreateTank(DemoOpenInfo info, Vector2D position,List<Body> result)
        {
            Lifespan avatarLifespan = new Lifespan();

            IShape shape = ShapeFactory.CreateSprite(Cache<SurfacePolygons>.GetItem("tank.png"), 4, 18, 2);

            ObjectIgnorer ignorer = new ObjectIgnorer();
            Body tankBody = new Body(new PhysicsState(new ALVector2D(0, 0, 0)),
                shape,
                300,//new MassInfo(40, Scalar.PositiveInfinity),
                new Coefficients(0, 1),
                avatarLifespan);
            result.Add(tankBody);
            tankBody.State.Position.Linear += position;
            tankBody.ApplyPosition();

            tankBody.CollisionIgnorer = ignorer;
            BodyGraphic graphic = CreateGraphic(tankBody);
            graphic.ZOrder = 2;
            info.Scene.AddGraphic(graphic);

            Scalar wheelSize = 18;
            Scalar wheelSpacing = -9;
            Scalar lenghtPercent = .84f;
            Matrix2x3 ident = Matrix2x3.Identity;
            BoundingRectangle rect;
            shape.CalcBoundingRectangle(ref ident, out rect);
            Scalar y = (rect.Max.Y + 4);
            Body lastWheel = null;
            BoundingPolygon polygon = new BoundingPolygon(shape.Vertexes);

            Ray ray2 = new Ray(new Vector2D(rect.Max.X, y), -Vector2D.YAxis);
            Scalar y3 = y - polygon.Intersects(ray2);
            Vector2D avatarBarrelOffset = new Vector2D(rect.Max.X + 10, y3);

            CircleShape wheelShape = ShapeFactory.CreateColoredCircle(wheelSize, 30);
            Scalar force = 0;

            for (Scalar x = rect.Min.X + wheelSize; x < (rect.Max.X - wheelSize) * lenghtPercent; x += (wheelSize * 2 + wheelSpacing))
            {

                Ray ray = new Ray(new Vector2D(x, y), -Vector2D.YAxis);
                Scalar y2 = y - polygon.Intersects(ray);



                Vector2D offset = new Vector2D(x, y2);

                Body wheel = new Body(
                    new PhysicsState(new ALVector2D(0, offset + position)),
                    wheelShape,
                    10,
                    new Coefficients(0, 3),//  coefficients.Duplicate(),
                    avatarLifespan);
                result.Add(wheel);

                wheel.CollisionIgnorer = ignorer;
                wheel.AngularDamping = .9f;
                wheel.Updated += delegate(object sender, UpdatedEventArgs e)
                {
                    wheel.State.ForceAccumulator.Angular += force;
                };
                info.Scene.AddGraphic(CreateGraphic(wheel));

                HingeJoint joint = new HingeJoint(tankBody, wheel, offset + position, avatarLifespan);
                joint.Softness = .1f;
                info.Scene.Engine.AddJoint(joint);

                if (lastWheel != null)
                {
                    AngleJoint joint2 = new AngleJoint(lastWheel, wheel, avatarLifespan);
                    info.Scene.Engine.AddJoint(joint2);
                }
                lastWheel = wheel;
            }


            CircleShape weaponShape = ShapeFactory.CreateColoredCircle(5, 8);

            //now begins the abuse of anominous delegates (BIG TIME)

            EventHandler<KeyboardEventArgs> keyDownHandler = delegate(object sender, KeyboardEventArgs e)
            {
                switch (e.Key)
                {
                    case Key.LeftArrow:
                        force = -1500000;
                        break;
                    case Key.RightArrow:
                        force = 1500000;
                        break;
                    case Key.Space:

                        Scalar velocity = 2000;

                        Matrix2x3 toWorld = tankBody.Matrices.ToWorld;
                        Matrix2x2 toWorldNormal = tankBody.Matrices.ToWorldNormal;

                        //  Matrix2D mat = avatarBodies[0].Matrices.ToWorld;
                        Vector2D direction = toWorldNormal * Vector2D.XAxis;
                        PhysicsState state = new PhysicsState();
                        state.Position.Linear = toWorld * (avatarBarrelOffset);
                        state.Velocity.Linear = velocity * direction + tankBody.State.Velocity.Linear;

                        Body weapon = new Body(state,
                            weaponShape,
                            5,
                            new Coefficients(1, 1),
                            new Lifespan(10));
                        //weapon.CollisionIgnorer = tankBody.CollisionIgnorer;

                        weapon.Collided += delegate(object sender2, CollisionEventArgs e2)
                        {
                            if (!weapon.Lifetime.IsExpired)
                            {
                                weapon.Lifetime.IsExpired = true;
                                AddParticles(info, weapon.State.Position.Linear, weapon.State.Velocity.Linear * .5f, 50);
                            }
                        };

                        //  weapon.Collided += weapon_Collided;
                        tankBody.State.Velocity.Linear -= (velocity * weapon.Mass.Mass * tankBody.Mass.MassInv) * direction;
                        info.Scene.AddGraphic(CreateGraphic(weapon));
                        break;
                }
            };
            EventHandler<KeyboardEventArgs> keyUpHandler = delegate(object sender, KeyboardEventArgs e)
            {
                switch (e.Key)
                {
                    case Key.LeftArrow:
                        force = 0;
                        break;
                    case Key.RightArrow:
                        force = 0;
                        break;
                }
            };
            Events.KeyboardDown += keyDownHandler;
            Events.KeyboardUp += keyUpHandler;

            return delegate()
            {
                Events.KeyboardDown -= keyDownHandler;
                Events.KeyboardUp -= keyUpHandler;
            };
        }
示例#37
0
 // Use this for initialization
 void Start()
 {
     this.myHingeJoint = GetComponent <HingeJoint>();
     SetAngle(this.defaultAngle);
 }
示例#38
0
        private void AddSlot(BaseGeneViewModel gene)
        {
            Will.Instance.RunPauseWilling(false);

            var slotGene = (NodeGeneViewModel)gene;

            var boneBody = Will.Instance.Bodies.RandomOrDefault<BoneBody>(b => b.Model.ChildSlots.Any(s => s.IsOccupied == false));

            if (boneBody == null)
            {
                Will.Instance.RunPauseWilling(true);
                return;
            }

            var parPos = boneBody.State.Position;

            var randSlot = boneBody.Model.ChildSlots.Where(s => s.IsOccupied == false).RandomOrDefault();

            var slot = slotGene.GetModelDuplicate();
            slot.Direction = randSlot.Direction;
            slot.DistanceFromCenter = randSlot.DistanceFromCenter;
            slot.Orientation = randSlot.Orientation;

            randSlot.IsOccupied = true;

            var slotBody = WillHelper.CreateConnectionSlotBody(slot, boneBody.ModelId);

            var slotXAngle = slot.Direction + parPos.Angular;
            var slotCenter = Vector2D.Rotate(slotXAngle, new Vector2D(slot.DistanceFromCenter, 0.0f));
            var slotPos = new ALVector2D(slot.Orientation + slotXAngle, slotCenter + parPos.Linear);

            slotBody.State.Position = slotPos;
            slotBody.ApplyPosition();

            slotBody.Parent = boneBody;

            boneBody.Children.Add(slotBody);

            var joints = new List<Joint>();

            var nodePos = slotBody.State.Position;

            var hinge = new HingeJoint(boneBody, slotBody, (slot.Size * nodePos.Linear + boneBody.Model.Length * parPos.Linear) * (1/(slot.Size + boneBody.Model.Length)), new Lifespan())
            {
                DistanceTolerance = 50,
                Softness = 10.1
            };
            var angle = new AngleJoint(boneBody, slotBody, new Lifespan()) { Softness = 0.00001 };

            joints.Add(hinge);
            joints.Add(angle);

            Will.Instance.AddBody(slotBody);
            Will.Instance.AddJoints(joints);

            Will.Instance.RunPauseWilling(true);
        }
示例#39
0
        void Create_Wheel(string direction, Vector3 position, int number)
        {
            // Create a new gameobject.
            GameObject gameObject = new GameObject("SupportWheel_" + direction + "_" + number);

            gameObject.transform.parent        = thisTransform;
            gameObject.transform.localPosition = position;
            if (direction == "L")
            {
                gameObject.transform.localRotation = Quaternion.Euler(Vector3.zero);
            }
            else
            {
                gameObject.transform.localRotation = Quaternion.Euler(0.0f, 0.0f, 180.0f);
            }
            gameObject.layer = PTS_Layer_Settings_CS.Wheels_Layer;             // Wheel
            // Mesh
            MeshFilter meshFilter = gameObject.AddComponent <MeshFilter> ();

            meshFilter.mesh = Wheel_MeshProp.objectReferenceValue as Mesh;
            MeshRenderer meshRenderer = gameObject.AddComponent <MeshRenderer> ();

            Material[] materials = new Material [Wheel_Materials_NumProp.intValue];
            for (int i = 0; i < materials.Length; i++)
            {
                materials [i] = Wheel_MaterialsProp.GetArrayElementAtIndex(i).objectReferenceValue as Material;
            }
            meshRenderer.materials = materials;
            // SphereCollider
            SphereCollider sphereCollider = gameObject.AddComponent <SphereCollider> ();

            sphereCollider.radius   = Wheel_RadiusProp.floatValue;
            sphereCollider.center   = Vector3.zero;
            sphereCollider.material = Collider_MaterialProp.objectReferenceValue as PhysicMaterial;
            // for Physics Wheel.
            if (Static_FlagProp.boolValue == false)
            {
                // Rigidbody
                Rigidbody rigidbody = gameObject.AddComponent <Rigidbody> ();
                rigidbody.mass = Wheel_MassProp.floatValue;
                // HingeJoint
                HingeJoint hingeJoint = gameObject.AddComponent <HingeJoint> ();
                hingeJoint.anchor        = Vector3.zero;
                hingeJoint.axis          = new Vector3(0.0f, 1.0f, 0.0f);
                hingeJoint.connectedBody = thisTransform.parent.gameObject.GetComponent <Rigidbody> ();
                // Drive_Wheel_CS
                PTS_Drive_Wheel_CS driveScript = gameObject.AddComponent <PTS_Drive_Wheel_CS> ();
                driveScript.Radius     = Wheel_RadiusProp.floatValue;
                driveScript.Drive_Flag = Drive_WheelProp.boolValue;
                // Wheel_Resize_CS
                if (Wheel_ResizeProp.boolValue)
                {
                    PTS_Wheel_Resize_CS resizeScript = gameObject.AddComponent <PTS_Wheel_Resize_CS> ();
                    resizeScript.ScaleDown_Size = ScaleDown_SizeProp.floatValue;
                    resizeScript.Return_Speed   = Return_SpeedProp.floatValue;
                }
                // Stabilizer_CS
                gameObject.AddComponent <PTS_Stabilizer_CS> ();
            }
            else                 // for Static Wheel
            {
                PTS_Static_Wheel_CS staticScript = gameObject.AddComponent <PTS_Static_Wheel_CS> ();
                staticScript.Radius_Offset = Radius_OffsetProp.floatValue;
            }
        }
示例#40
0
文件: Demo.cs 项目: bsvercl/physics2d
        void Demo6()
        {
            BeginDemoChange();
            Reset();
            AddGravityField();

            List<Body> chain = AddChain(new Vector2D(400, 50), 100, 30, 200, 20, 800);
            Vector2D point = new Vector2D(300, 50);

            Body Anchor = AddCircle(30, 18, Scalar.PositiveInfinity, new ALVector2D(0, point));
            Anchor.IgnoresGravity = true;
            HingeJoint joint = new HingeJoint(chain[0], Anchor, point, new Lifespan());
            joint.DistanceTolerance = 10;
            engine.AddJoint(joint);
            EndDemoChange();
        }
 private void Start()
 {
     _hingeJoint = GetComponent <HingeJoint>();
     newAngle    = 0;
     prevAngle   = 0;
 }
示例#42
0
文件: Demo.cs 项目: bsvercl/physics2d
        void Demo8()
        {
            BeginDemoChange();
            Reset();
            AddGravityField();

            Scalar boxlength = 50;
            Scalar spacing = 4;
            Scalar anchorLenght = 30;
            Scalar anchorGap = (boxlength / 2) + spacing + (anchorLenght / 2);
            List<Body> chain = AddChain(new Vector2D(200, 500), boxlength, 20, 200, spacing, 600);

            Vector2D point2 = new Vector2D(chain[chain.Count - 1].State.Position.Linear.X + anchorGap, 500);
            Body end2 = AddCircle(anchorLenght / 2, 14, Scalar.PositiveInfinity, new ALVector2D(0, point2));
            end2.IgnoresGravity = true;
            HingeJoint joint2 = new HingeJoint(chain[chain.Count - 1], end2, point2, new Lifespan());
            joint2.DistanceTolerance = 10;
            engine.AddJoint(joint2);

            Vector2D point1 = new Vector2D(chain[0].State.Position.Linear.X - anchorGap, 500);
            Body end1 = AddCircle(anchorLenght/2, 14, Scalar.PositiveInfinity, new ALVector2D(0, point1));
            end1.IgnoresGravity = true;
            HingeJoint joint1 = new HingeJoint(chain[0], end1, point1, new Lifespan());
            joint1.DistanceTolerance = 10;
            engine.AddJoint(joint1);
            end2.State.Position.Linear.X -= 10;
            end1.State.Position.Linear.X += 10;
            end2.ApplyPosition();
            end1.ApplyPosition();

            AddTower2();


            EndDemoChange();
        }