Inheritance: Enemy
Ejemplo n.º 1
0
 public CharacterAppearance()
 {
     Head = new Limb();
     Body = new Limb();
     LeftLeg = new Limb();
     RightLeg = new Limb();
     LeftArm = new Limb();
     RightArm = new Limb();
 }
Ejemplo n.º 2
0
        public Sprite CreateLimp(Limb limb, Character character)
        {
            Sprite result = new Sprite(
                parent: character,
                textureId: limb.TextureId,
                size: limb.Size,
                collidable: false,
                elasticity: 0);

            result.RotationAngle = limb.RotationAngle;
            result.RotationOrigin = limb.RotationOrigin;
            result.LayerDepth = limb.LayerDepth;

            character.Add(result, limb.Position);

            return result;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Returns true if the attack successfully hit something. If the distance is not given, it will be calculated.
        /// </summary>
        public bool UpdateAttack(float deltaTime, Vector2 attackSimPos, IDamageable damageTarget, out AttackResult attackResult, float distance = -1, Limb targetLimb = null)
        {
            attackResult = default(AttackResult);
            Vector2 simPos     = ragdoll.SimplePhysicsEnabled ? character.SimPosition : SimPosition;
            float   dist       = distance > -1 ? distance : ConvertUnits.ToDisplayUnits(Vector2.Distance(simPos, attackSimPos));
            bool    wasRunning = attack.IsRunning;

            attack.UpdateAttackTimer(deltaTime, character);

            bool wasHit        = false;
            Body structureBody = null;

            if (damageTarget != null)
            {
                switch (attack.HitDetectionType)
                {
                case HitDetection.Distance:
                    if (dist < attack.DamageRange)
                    {
                        structureBody = Submarine.PickBody(simPos, attackSimPos, collisionCategory: Physics.CollisionWall | Physics.CollisionLevel, allowInsideFixture: true);
                        if (structureBody?.UserData as string == "ruinroom")
                        {
                            structureBody = null;
                        }
                        if (damageTarget is Item i && i.GetComponent <Items.Components.Door>() != null)
                        {
                            // If the attack is aimed to an item and hits an item, it's successful.
                            // Ignore blocking checks on doors, because it causes cases where a Mudraptor cannot hit the hatch, for example.
                            wasHit = true;
                        }
                        else if (damageTarget is Structure wall && structureBody != null &&
                                 (structureBody.UserData is Structure || (structureBody.UserData is Submarine sub && sub == wall.Submarine)))
                        {
                            // If the attack is aimed to a structure (wall) and hits a structure or the sub, it's successful
                            wasHit = true;
                        }
                        else
                        {
                            // If there is nothing between, the hit is successful
                            wasHit = structureBody == null;
                        }
                    }
Ejemplo n.º 4
0
    void LoadBot(string path)
    {
        //SceneManager.LoadScene("empty");


        GameObject canvas = GameObject.Find("Canvas");

        canvas.name = "Canvas Del";
        GameObject.DestroyImmediate(canvas);
        UnityEngine.Object cPrefab = Resources.Load("Canvas");
        canvas      = (GameObject)GameObject.Instantiate(cPrefab, new Vector3(0, 0, 0), Quaternion.identity);
        canvas.name = "Canvas";
        Debug.Log(path);
        GameObject parentObj = GameObject.Find("GameObject");

        parentObj.name = "GameObject Del";
        int childs = parentObj.transform.childCount;

        /*for (int i = childs - 1; i >= 0; i--)
         * {
         *      GameObject.DestroyImmediate(transform.GetChild(i).gameObject);
         * }*/
        GameObject.DestroyImmediate(parentObj);
        parentObj = new GameObject("GameObject");
        parentObj.AddComponent <Serial>();
        parentObj.name = "GameObject";
        InverseKinematics ik = parentObj.AddComponent <InverseKinematics>();

        //DontDestroyOnLoad(parentObj);
        UnityEngine.Object bPrefab = Resources.Load("Button");
        GameObject         newButt = (GameObject)GameObject.Instantiate(bPrefab, new Vector3(-109f, -75, 0), Quaternion.identity);

        newButt.transform.SetParent(GameObject.Find("Canvas").transform, false);
        newButt.GetComponentInChildren <Text>().text = "Inverse Kinematics";
        newButt.name = "IK";
        newButt.transform.GetComponent <RectTransform>().anchorMin = new Vector2(1, 1);
        newButt.transform.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1);
        //newButt.GetComponent<Button>().onClick.AddListener(delegate { Load(); });
        newButt.GetComponent <Button>().onClick.AddListener(() => ik.btn_StartIK());
        var sr           = new StreamReader(path);
        var fileContents = sr.ReadToEnd();

        sr.Close();

        string [,] inputs = new string[50, 10];
        var lines = fileContents.Split("\n"[0]);
        int count = 0;

        foreach (string line in lines)
        {
            var lineElements = line.Split(" "[0]);
            int count2       = 0;
            foreach (string word in lineElements)
            {
                //Debug.Log(word);
                inputs[count, count2] = word;
                count2++;
            }
            Debug.Log(count + " " + line);
            count++;
        }

        int sliderCount = 0;
        int armsNo      = Int32.Parse(inputs[0, 0]);

        ik.jointCount = armsNo + 1;
        for (int i = 0; i < armsNo; i++)
        {
            //Debug.Log(inputs[3*armsNo+1+1,0]);
            //Debug.Log(ToLiteral(inputs[3*armsNo+1+1,0]));
            //Debug.Log("C:/Users/Victor/Documents/untitled.obj");
            //Debug.Log(ToLiteral("C:/Users/Victor/Documents/untitled.obj"));
            GameObject obj = loadAndDisplayMesh(inputs[3 * armsNo + 1 + 1 + i, 0].Replace("\r", ""));
            obj.transform.SetParent(parentObj.transform);
            obj.name = i.ToString() + "," + (i + 1).ToString();
            //obj.AddComponent<MeshCollider>();
            //obj.GetComponent<MeshCollider>().convex = true;
            var colli = obj.AddComponent <NonConvexMeshCollider>();
            colli.avoidExceedingMesh = true;
            colli.boxesPerEdge       = 20;
            colli.Calculate();
            Limb lmb = obj.AddComponent <Limb>();
            lmb.otherScale = Int32.Parse(inputs[i + 1, 0]);
            Debug.Log(inputs[5 * armsNo + 9 + i, 0]);;
            lmb.overlap = float.Parse(inputs[5 * armsNo + 9 + i, 0], CultureInfo.InvariantCulture);
            lmb.offsetX = float.Parse(inputs[6 * armsNo + 9 + i, 0], CultureInfo.InvariantCulture);
            GameObject obj2 = loadAndDisplayMesh(inputs[4 * armsNo + 3, 0].Replace("\r", ""));
            //obj2.transform.Rotate(new Vector3(Int32.Parse(inputs[armsNo*2+1+i,0]), Int32.Parse(inputs[armsNo*2+1+i,1]), Int32.Parse(inputs[armsNo*2+1+i,2])));
            obj2.AddComponent <MeshCollider>();
            obj2.GetComponent <MeshCollider>().convex = true;
            obj2.transform.SetParent(parentObj.transform);
            obj2.name = i.ToString();
            if (i == 0)
            {
                RoboJoint rbj2 = obj2.AddComponent <RoboJoint>();
                int       refX = Int32.Parse(inputs[7 * armsNo + 14 + i, 0]);
                int       refY = Int32.Parse(inputs[7 * armsNo + 14 + i, 1]);
                int       refZ = Int32.Parse(inputs[7 * armsNo + 14 + i, 2]);
                rbj2.q2   = Quaternion.Euler(refX, refY, refZ);
                rbj2.yOff = float.Parse(inputs[7 * armsNo + 9, 1], CultureInfo.InvariantCulture);
            }
            else
            {
                RoboJoint3 rbj2 = obj2.AddComponent <RoboJoint3>();
                rbj2.length = Int32.Parse(inputs[armsNo + i, 0]);
                rbj2.d      = float.Parse(inputs[armsNo + i, 1], CultureInfo.InvariantCulture);
                rbj2.xRot   = Int32.Parse(inputs[armsNo * 2 + 1 + i, 0]);
                rbj2.yRot   = Int32.Parse(inputs[armsNo * 2 + 1 + i, 1]);
                rbj2.zRot   = Int32.Parse(inputs[armsNo * 2 + 1 + i, 2]);

                //rbj2.theta = float.Parse(inputs[armsNo+i,1], CultureInfo.InvariantCulture);
                //rbj2.alpha = float.Parse(inputs[armsNo+i,2], CultureInfo.InvariantCulture);
                int refX = Int32.Parse(inputs[7 * armsNo + 14 + i, 0]);
                int refY = Int32.Parse(inputs[7 * armsNo + 14 + i, 1]);
                int refZ = Int32.Parse(inputs[7 * armsNo + 14 + i, 2]);
                rbj2.q2 = Quaternion.Euler(refX, refY, refZ);
            }

            Debug.Log("Joint to render: " + i);
            Debug.Log(" value:  " + inputs[7 * armsNo + 11, i]);
            if (inputs[7 * armsNo + 11, i].Trim() == "0")
            {
                obj2.GetComponent <MeshRenderer>().enabled = false;
                obj2.GetComponent <Collider>().enabled     = false;
            }
            UnityEngine.Object pPrefab   = Resources.Load("Slider (1)");   // note: not .prefab!
            GameObject         newSlider = (GameObject)GameObject.Instantiate(pPrefab, new Vector3(98, -10 - sliderCount * 20, 0), Quaternion.identity);
            //GameObject newSlider = Instantiate(Slider) as GameObject;
            sliderCount++;
            newSlider.transform.SetParent(GameObject.Find("Canvas").transform, false);
            newSlider.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
            newSlider.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
            newSlider.name = "Slider (" + (2 * i).ToString() + ")";
            //newSlider.GetComponent<Slider>().label = "Slider (" + (i).ToString() + ") Theta";
            if (inputs[4 * armsNo + 4 + i, 0] == "0")
            {
                newSlider.GetComponent <Slider>().interactable      = false;
                newSlider.GetComponent <RectTransform>().localScale = new Vector3(0f, 0f, 0f);
                ;
                sliderCount--;
            }
            else
            {
                GameObject textObj = new GameObject("myTextGO");
                textObj.transform.position = new Vector3(229.4f, -30.4f - sliderCount * 20, 0);
                textObj.transform.SetParent(GameObject.Find("Canvas").transform, false);
                //textObj.transform.SetParent(newSlider.transform);
                Text myText = textObj.AddComponent <Text>();
                myText.text = "Arm " + (i).ToString() + "- Theta";
                myText.font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
                textObj.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
                textObj.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
                if (i < armsNo)
                {
                    //if (i >0){
                    //newSlider.GetComponent<Slider>().value = float.Parse(inputs[armsNo+i,2], CultureInfo.InvariantCulture);
                    newSlider.GetComponent <Slider>().value = float.Parse(inputs[armsNo + i + 1, 2], CultureInfo.InvariantCulture);
                }
            }
            GameObject newSlider2 = (GameObject)GameObject.Instantiate(pPrefab, new Vector3(98, -10 - sliderCount * 20, 0), Quaternion.identity);
            //GameObject newSlider = Instantiate(Slider) as GameObject;
            sliderCount++;
            newSlider2.transform.SetParent(GameObject.Find("Canvas").transform, false);
            newSlider2.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
            newSlider2.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
            newSlider2.name = "Slider (" + (2 * i + 1).ToString() + ")";
            //newSlider2.label = "Slider (" + (i).ToString() + ") Alpha";
            if (inputs[4 * armsNo + 4 + i, 1] == "0")
            {
                sliderCount--;
                newSlider2.GetComponent <Slider>().interactable      = false;
                newSlider2.GetComponent <RectTransform>().localScale = new Vector3(0f, 0f, 0f);
            }
            else
            {
                GameObject textObj = new GameObject("myTextGO");
                textObj.transform.position = new Vector3(229.4f, -30.4f - sliderCount * 20, 0);
                textObj.transform.SetParent(GameObject.Find("Canvas").transform, false);
                //textObj.transform.SetParent(newSlider2.transform);
                //textObj.transform.localPosition = new Vector3(198.6f,-43f,0f);
                Debug.Log(newSlider2.name);
                Text myText = textObj.AddComponent <Text>();
                myText.text = "Arm " + (i).ToString() + "- Alpha";
                myText.font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
                textObj.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
                textObj.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
                //if (i > 0){
                //newSlider2.GetComponent<Slider>().value = float.Parse(inputs[armsNo+i,3], CultureInfo.InvariantCulture);
                if (i < armsNo)
                {
                    newSlider2.GetComponent <Slider>().value = float.Parse(inputs[armsNo + i + 1, 3], CultureInfo.InvariantCulture);
                }
            }
            GameObject newSlider8 = (GameObject)GameObject.Instantiate(pPrefab, new Vector3(98, -10 - sliderCount * 20, 0), Quaternion.identity);
            //GameObject newSlider = Instantiate(Slider) as GameObject;
            //sliderCount ++;
            //newSlider8.transform.SetParent(GameObject.Find("Canvas").transform, false);
            newSlider8.name = "Slider (l" + (2 * i).ToString() + ")";
            newSlider8.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
            newSlider8.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
            //newSlider2.label = "Slider (" + (i).ToString() + ") Alpha";
            if (inputs[4 * armsNo + 4 + i, 2] == "0")
            {
                sliderCount--;
                newSlider8.GetComponent <Slider>().interactable      = false;
                newSlider8.GetComponent <RectTransform>().localScale = new Vector3(0f, 0f, 0f);
                newSlider8.GetComponent <Slider>().maxValue          = 2 * float.Parse(inputs[armsNo + i, 0], CultureInfo.InvariantCulture);
                newSlider8.GetComponent <Slider>().minValue          = float.Parse(inputs[armsNo + i, 0], CultureInfo.InvariantCulture);
                newSlider8.GetComponent <Slider>().value             = float.Parse(inputs[armsNo + i, 0], CultureInfo.InvariantCulture);
                ;
            }
            else
            {
                //GameObject textObj = new GameObject("myTextGO");
                //textObj.transform.position = new Vector3(229.4f, -30.4f -sliderCount*20, 0);
                //textObj.transform.SetParent(GameObject.Find("Canvas").transform, false);
                //textObj.transform.SetParent(newSlider8.transform);
                //textObj.transform.localPosition = new Vector3(198.6f,-43f,0f);
                //Text myText = textObj.AddComponent<Text>();
                //myText.text = "Slider (" + (i).ToString() + ") length";
                //myText.font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
                //myText.horizontalOverflow = HorizontalWrapMode.Overflow;
                //textObj.transform.GetComponent<RectTransform>().anchorMin = new Vector2(0,1);
                //textObj.transform.GetComponent<RectTransform>().anchorMax = new Vector2(0,1);
                //newSlider8.GetComponent<RectTransform>().SetSizeWithCurrentAnchors( RectTranform.Axis.Horizontal, 150);
            }
        }

        GameObject obj3 = loadAndDisplayMesh(inputs[5 * armsNo + 6, 0].Replace("\r", ""));

        obj3.AddComponent <MeshCollider>();
        obj3.GetComponent <MeshCollider>().convex = true;
        obj3.name = (armsNo).ToString();
        var colli3 = obj3.AddComponent <NonConvexMeshCollider>();

        colli3.avoidExceedingMesh = true;
        colli3.boxesPerEdge       = 20;
        //colli3.Calculate();
        //obj3.AddComponent<MeshCollider>();
        RoboJoint3 rbj3  = obj3.AddComponent <RoboJoint3>();
        int        refX3 = Int32.Parse(inputs[8 * armsNo + 14, 0]);
        int        refY3 = Int32.Parse(inputs[8 * armsNo + 14, 1]);
        int        refZ3 = Int32.Parse(inputs[8 * armsNo + 14, 2]);

        rbj3.q2     = Quaternion.Euler(refX3, refY3, refZ3);
        rbj3.length = Int32.Parse(inputs[armsNo * 2, 0]);
        Debug.Log(inputs[armsNo * 2, 1]);
        rbj3.d          = float.Parse(inputs[armsNo * 2, 1], CultureInfo.InvariantCulture);
        rbj3.otherScale = Int32.Parse(inputs[armsNo, 2]);
        obj3.transform.SetParent(parentObj.transform);
        //Debug.Log(" HERHE " + (inputs[7*armsNo+12,0].Contains("0")));
        //Debug.Log(" HERHE " + (String.Compare(inputs[7*armsNo+12,0],"1")));
        if (inputs[7 * armsNo + 12, 0].Contains("1"))
        {
            rbj3.rotGripper = false;
        }
        UnityEngine.Object pPrefab2   = Resources.Load("Slider (1)");       // note: not .prefab!
        GameObject         newSlider3 = (GameObject)GameObject.Instantiate(pPrefab2, new Vector3(98, -10 - sliderCount * 20, 0), Quaternion.identity);

        sliderCount++;
        //GameObject newSlider = Instantiate(Slider) as GameObject;
        newSlider3.transform.SetParent(GameObject.Find("Canvas").transform, false);
        newSlider3.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
        newSlider3.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
        newSlider3.name = "Slider (" + (2 * armsNo).ToString() + ")";
        //newSlider3.label = "Slider (" + (armsNo).ToString() + ") Theta";
        if (inputs[4 * armsNo + 4 + armsNo, 0] == "0")
        {
            sliderCount--;
            newSlider3.GetComponent <Slider>().interactable      = false;
            newSlider3.GetComponent <RectTransform>().localScale = new Vector3(0f, 0f, 0f);
        }
        else
        {
            GameObject textObj = new GameObject("myTextGO");
            textObj.transform.position = new Vector3(229.4f, -30.4f - sliderCount * 20, 0);
            textObj.transform.SetParent(GameObject.Find("Canvas").transform, false);
            //textObj.transform.SetParent(newSlider3.transform);
            //textObj.transform.localPosition = new Vector3(198.6f,-43f,0f);
            Text myText = textObj.AddComponent <Text>();
            myText.text = "Hand " + (armsNo).ToString() + "- Theta";
            myText.font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
            textObj.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
            textObj.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
            newSlider3.GetComponent <Slider>().value = float.Parse(inputs[armsNo * 2, 2], CultureInfo.InvariantCulture);
        }
        GameObject newSlider4 = (GameObject)GameObject.Instantiate(pPrefab2, new Vector3(98, -10 - sliderCount * 20, 0), Quaternion.identity);

        sliderCount++;
        //GameObject newSlider = Instantiate(Slider) as GameObject;
        newSlider4.transform.SetParent(GameObject.Find("Canvas").transform, false);
        newSlider4.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
        newSlider4.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
        newSlider4.name = "Slider (" + (2 * armsNo + 1).ToString() + ")";
        //newSlider4.label = "Slider (" + (armsNo).ToString() + ") Alpha";
        if (inputs[4 * armsNo + 4 + armsNo, 1] == "0")
        {
            sliderCount--;
            newSlider4.GetComponent <Slider>().interactable      = false;
            newSlider4.GetComponent <RectTransform>().localScale = new Vector3(0f, 0f, 0f);
        }
        else
        {
            GameObject textObj = new GameObject("myTextGO");
            textObj.transform.position = new Vector3(229.4f, -30.4f - sliderCount * 20, 0);
            textObj.transform.SetParent(GameObject.Find("Canvas").transform, false);
            //textObj.transform.SetParent(newSlider4.transform);
            //textObj.transform.localPosition = new Vector3(198.6f,-43f,0f);
            Text myText = textObj.AddComponent <Text>();
            myText.text = "Hand " + (armsNo).ToString() + "- Alpha";
            myText.font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
            textObj.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
            textObj.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
            newSlider4.GetComponent <Slider>().value = float.Parse(inputs[armsNo * 2, 2], CultureInfo.InvariantCulture);
        }


        //Debug.Log(inputs[5*armsNo+6,0].Replace("\r", ""));

        /*GameObject obj4 = loadAndDisplayMesh(inputs[4*armsNo+7,0].Replace("\r", ""));
         * obj4.AddComponent<MeshCollider>();
         * obj4.GetComponent<MeshCollider>().convex = true;
         * obj4.name = "grabber";
         * //obj3.AddComponent<MeshCollider>();
         * grabber g4 = obj4.AddComponent<grabber>();
         * //rbj3.length = Int32.Parse(inputs[armsNo*2,0]);
         * //rbj3.d = Int32.Parse(inputs[armsNo*2,1]);
         * obj4.transform.SetParent(parentObj.transform);
         * g4.parent = obj3;*/

        GameObject newSlider5 = (GameObject)GameObject.Instantiate(pPrefab2, new Vector3(98, -10 - sliderCount * 20, 0), Quaternion.identity);

        sliderCount++;
        //GameObject newSlider = Instantiate(Slider) as GameObject;
        newSlider5.transform.SetParent(GameObject.Find("Canvas").transform, false);
        newSlider5.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
        newSlider5.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
        newSlider5.name = "Slider (" + (2 * armsNo + 2).ToString() + ")";
        newSlider5.GetComponent <Slider>().maxValue = 100f;
        newSlider5.GetComponent <Slider>().minValue = 30f;
        newSlider5.GetComponent <Slider>().value    = 100f;
        //newSlider4.label = "Slider (" + (armsNo).ToString() + ") Alpha";
        GameObject textObj2 = new GameObject("myTextGO");

        textObj2.transform.position = new Vector3(229.4f, -30.4f - sliderCount * 20, 0);
        textObj2.transform.SetParent(GameObject.Find("Canvas").transform, false);
        //textObj2.transform.SetParent(newSlider5.transform);
        //textObj2.transform.localPosition = new Vector3(198.6f,-43f,0f);
        Text myText2 = textObj2.AddComponent <Text>();

        myText2.text = "Slider grab";
        myText2.font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
        textObj2.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
        textObj2.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);

        GameObject newSlider9 = (GameObject)GameObject.Instantiate(pPrefab2, new Vector3(98, -10 - sliderCount * 20, 0), Quaternion.identity);

        //GameObject newSlider = Instantiate(Slider) as GameObject;
        //sliderCount ++;
        //newSlider9.transform.SetParent(GameObject.Find("Canvas").transform, false);
        newSlider9.name = "Slider (l" + (2 * armsNo).ToString() + ")";
        newSlider9.transform.GetComponent <RectTransform>().anchorMin = new Vector2(0, 1);
        newSlider9.transform.GetComponent <RectTransform>().anchorMax = new Vector2(0, 1);
        //newSlider2.label = "Slider (" + (i).ToString() + ") Alpha";
        Debug.Log(" ASDasdas" + inputs[5 * armsNo + 4, 2]);
        if (inputs[5 * armsNo + 4, 2] == "0")
        {
            sliderCount--;
            newSlider9.GetComponent <Slider>().interactable      = false;
            newSlider9.GetComponent <RectTransform>().localScale = new Vector3(0f, 0f, 0f);
            ;
        }
        else
        {
            //GameObject textObj = new GameObject("myTextGO");
            //textObj.transform.position = new Vector3(229.4f, -30.4f -sliderCount*20, 0);
            //textObj.transform.SetParent(GameObject.Find("Canvas").transform, false);
            //textObj.transform.SetParent(newSlider9.transform);
            //textObj.transform.localPosition = new Vector3(198.6f,-43f,0f);
            //Text myText = textObj.AddComponent<Text>();
            //myText.text = "Slider (" + (armsNo).ToString() + ") length";
            //myText.font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
            //myText.horizontalOverflow = HorizontalWrapMode.Overflow;
            //textObj.transform.GetComponent<RectTransform>().anchorMin = new Vector2(0,1);
            //textObj.transform.GetComponent<RectTransform>().anchorMax = new Vector2(0,1);
            newSlider9.GetComponent <Slider>().maxValue = 2 * float.Parse(inputs[armsNo * 2, 0], CultureInfo.InvariantCulture);
            newSlider9.GetComponent <Slider>().minValue = float.Parse(inputs[armsNo * 2, 0], CultureInfo.InvariantCulture);
            newSlider9.GetComponent <Slider>().value    = float.Parse(inputs[armsNo * 2, 0], CultureInfo.InvariantCulture);
            //newSlider8.GetComponent<RectTransform>().SetSizeWithCurrentAnchors( RectTranform.Axis.Horizontal, 150);
        }



        GameObject obj5 = loadAndDisplayMesh(inputs[5 * armsNo + 7, 0].Replace("\r", ""));

        obj5.AddComponent <MeshCollider>();
        obj5.GetComponent <MeshCollider>().convex = true;
        obj5.name = "hand 1";
        //obj3.AddComponent<MeshCollider>();
        grabberHand gh5 = obj5.AddComponent <grabberHand>();

        //rbj3.length = Int32.Parse(inputs[armsNo*2,0]);
        //rbj3.d = Int32.Parse(inputs[armsNo*2,1]);
        obj5.transform.SetParent(parentObj.transform);
        gh5.parent      = obj3;
        gh5.jointParent = obj3;
        gh5.offsets.x   = float.Parse(inputs[7 * armsNo + 13, 0], CultureInfo.InvariantCulture);
        gh5.offsets.y   = float.Parse(inputs[7 * armsNo + 13, 1], CultureInfo.InvariantCulture);
        gh5.offsets.z   = float.Parse(inputs[7 * armsNo + 13, 2], CultureInfo.InvariantCulture);

        //gh5.xscale = 2f;

        gh5.sliderNo = newSlider5.name;

        GameObject obj6 = loadAndDisplayMesh(inputs[5 * armsNo + 8, 0].Replace("\r", ""));

        obj6.AddComponent <MeshCollider>();
        obj6.GetComponent <MeshCollider>().convex = true;
        obj6.name = "hand 2";
        //obj3.AddComponent<MeshCollider>();
        grabberHand gh6 = obj6.AddComponent <grabberHand>();

        //rbj3.length = Int32.Parse(inputs[armsNo*2,0]);
        //rbj3.d = Int32.Parse(inputs[armsNo*2,1]);
        obj6.transform.SetParent(parentObj.transform);
        gh6.parent      = obj3;
        gh6.jointParent = obj3;
        gh6.xscale      = 2f;
        gh6.sliderNo    = gh5.sliderNo;
        gh6.offsets.x   = float.Parse(inputs[7 * armsNo + 13, 0], CultureInfo.InvariantCulture);
        gh6.offsets.y   = float.Parse(inputs[7 * armsNo + 13, 1], CultureInfo.InvariantCulture);
        gh6.offsets.z   = float.Parse(inputs[7 * armsNo + 13, 2], CultureInfo.InvariantCulture);



        GameObject obj7 = loadAndDisplayMesh(inputs[4 * armsNo + 2, 0].Replace("\r", ""));

        //obj7.AddComponent<MeshCollider>();
        //obj7.GetComponent<MeshCollider>().convex = true;
        obj7.name = "base";
        //obj3.AddComponent<MeshCollider>();
        var colli7 = obj7.AddComponent <NonConvexMeshCollider>();

        colli7.avoidExceedingMesh = true;
        colli7.boxesPerEdge       = 30;
        //colli7.Calculate();
        Base b7 = obj7.AddComponent <Base>();

        b7.offset.x = float.Parse(inputs[7 * armsNo + 9, 0], CultureInfo.InvariantCulture);
        b7.offset.y = float.Parse(inputs[7 * armsNo + 9, 1], CultureInfo.InvariantCulture);
        b7.offset.z = float.Parse(inputs[7 * armsNo + 9, 2], CultureInfo.InvariantCulture);
        b7.scale    = float.Parse(inputs[7 * armsNo + 10, 0], CultureInfo.InvariantCulture);

        int        bitsNo = Int32.Parse(inputs[8 * armsNo + 15, 0]);
        GameObject obj8;

        for (int k = 0; k < bitsNo; k++)
        {
            Debug.Log(inputs[8 * armsNo + 15 + k, 0].Replace("\r", ""));
            obj8 = loadAndDisplayMesh(inputs[8 * armsNo + 16 + k, 0].Replace("\r", ""));
            //obj8.AddComponent<MeshCollider>();
            //obj8.GetComponent<MeshCollider>().convex = true;
            obj8.name = "bit" + k.ToString();
            Bits bit = obj8.AddComponent <Bits>();
            bit.jointNum    = (inputs[8 * armsNo + 16 + k, 1].Replace("\r", ""));
            bit.jointRotNum = Int32.Parse(inputs[8 * armsNo + 16 + k, 2].Replace("\r", ""));
            bit.scale       = float.Parse(inputs[8 * armsNo + 16 + k, 3].Replace("\r", ""));
            bit.offset.x    = float.Parse(inputs[8 * armsNo + 16 + k, 4].Replace("\r", ""));
            bit.offset.y    = float.Parse(inputs[8 * armsNo + 16 + k, 5].Replace("\r", ""));
            bit.offset.z    = float.Parse(inputs[8 * armsNo + 16 + k, 6].Replace("\r", ""));
            bit.useLocal    = Int32.Parse(inputs[8 * armsNo + 16 + k, 7].Replace("\r", ""));
        }
    }
Ejemplo n.º 5
0
        private bool FixBody(Character user, float deltaTime, float degreeOfSuccess, Body targetBody)
        {
            if (targetBody?.UserData == null)
            {
                return(false);
            }

            pickedPosition = Submarine.LastPickedPosition;

            if (targetBody.UserData is Structure targetStructure)
            {
                if (targetStructure.IsPlatform)
                {
                    return(false);
                }
                int sectionIndex = targetStructure.FindSectionIndex(ConvertUnits.ToDisplayUnits(pickedPosition));
                if (sectionIndex < 0)
                {
                    return(false);
                }

                if (!fixableEntities.Contains("structure") && !fixableEntities.Contains(targetStructure.Prefab.Identifier))
                {
                    return(true);
                }

                ApplyStatusEffectsOnTarget(user, deltaTime, ActionType.OnUse, new ISerializableEntity[] { targetStructure });
                FixStructureProjSpecific(user, deltaTime, targetStructure, sectionIndex);
                targetStructure.AddDamage(sectionIndex, -StructureFixAmount * degreeOfSuccess, user);

                //if the next section is small enough, apply the effect to it as well
                //(to make it easier to fix a small "left-over" section)
                for (int i = -1; i < 2; i += 2)
                {
                    int nextSectionLength = targetStructure.SectionLength(sectionIndex + i);
                    if ((sectionIndex == 1 && i == -1) ||
                        (sectionIndex == targetStructure.SectionCount - 2 && i == 1) ||
                        (nextSectionLength > 0 && nextSectionLength < Structure.WallSectionSize * 0.3f))
                    {
                        //targetStructure.HighLightSection(sectionIndex + i);
                        targetStructure.AddDamage(sectionIndex + i, -StructureFixAmount * degreeOfSuccess);
                    }
                }
                return(true);
            }
            else if (targetBody.UserData is Character targetCharacter)
            {
                if (targetCharacter.Removed)
                {
                    return(false);
                }
                targetCharacter.LastDamageSource = item;
                Limb  closestLimb = null;
                float closestDist = float.MaxValue;
                foreach (Limb limb in targetCharacter.AnimController.Limbs)
                {
                    float dist = Vector2.DistanceSquared(item.SimPosition, limb.SimPosition);
                    if (dist < closestDist)
                    {
                        closestLimb = limb;
                        closestDist = dist;
                    }
                }

                if (closestLimb != null && !MathUtils.NearlyEqual(TargetForce, 0.0f))
                {
                    Vector2 dir = closestLimb.WorldPosition - item.WorldPosition;
                    dir = dir.LengthSquared() < 0.0001f ? Vector2.UnitY : Vector2.Normalize(dir);
                    closestLimb.body.ApplyForce(dir * TargetForce, maxVelocity: 10.0f);
                }

                ApplyStatusEffectsOnTarget(user, deltaTime, ActionType.OnUse,
                                           closestLimb == null ? new ISerializableEntity[] { targetCharacter } : new ISerializableEntity[] { targetCharacter, closestLimb });
                FixCharacterProjSpecific(user, deltaTime, targetCharacter);
                return(true);
            }
            else if (targetBody.UserData is Limb targetLimb)
            {
                if (targetLimb.character == null || targetLimb.character.Removed)
                {
                    return(false);
                }

                if (!MathUtils.NearlyEqual(TargetForce, 0.0f))
                {
                    Vector2 dir = targetLimb.WorldPosition - item.WorldPosition;
                    dir = dir.LengthSquared() < 0.0001f ? Vector2.UnitY : Vector2.Normalize(dir);
                    targetLimb.body.ApplyForce(dir * TargetForce, maxVelocity: 10.0f);
                }

                targetLimb.character.LastDamageSource = item;
                ApplyStatusEffectsOnTarget(user, deltaTime, ActionType.OnUse, new ISerializableEntity[] { targetLimb.character, targetLimb });
                FixCharacterProjSpecific(user, deltaTime, targetLimb.character);
                return(true);
            }
            else if (targetBody.UserData is Item targetItem)
            {
                targetItem.IsHighlighted = true;

                ApplyStatusEffectsOnTarget(user, deltaTime, ActionType.OnUse, targetItem.AllPropertyObjects);

                if (targetItem.body != null && !MathUtils.NearlyEqual(TargetForce, 0.0f))
                {
                    Vector2 dir = targetItem.WorldPosition - item.WorldPosition;
                    dir = dir.LengthSquared() < 0.0001f ? Vector2.UnitY : Vector2.Normalize(dir);
                    targetItem.body.ApplyForce(dir * TargetForce, maxVelocity: 10.0f);
                }

                var levelResource = targetItem.GetComponent <LevelResource>();
                if (levelResource != null && levelResource.IsActive &&
                    levelResource.requiredItems.Any() &&
                    levelResource.HasRequiredItems(user, addMessage: false))
                {
                    levelResource.DeattachTimer += deltaTime;
#if CLIENT
                    Character.Controlled?.UpdateHUDProgressBar(
                        this,
                        targetItem.WorldPosition,
                        levelResource.DeattachTimer / levelResource.DeattachDuration,
                        Color.Red, Color.Green);
#endif
                }
                FixItemProjSpecific(user, deltaTime, targetItem);
                return(true);
            }
            return(false);
        }
Ejemplo n.º 6
0
 public void wound_by_section(Limb bodyPart, ref List<string> wReport)
 {
     bodyPart.consolidate_injury_report(ref wReport);
     if (bodyPart.is_disabled())
         wReport.Add("It is useless");
 }
Ejemplo n.º 7
0
				void _LimbTranslateBeginOnly( Limb limb, ref Vector3 origTranslate )
				{
					for( int i = 0; i < 2; ++i ) {
						limb.beginPos[i] += origTranslate;
					}
				}
Ejemplo n.º 8
0
    protected override void Update()
    {
        base.Update();
        this.m_BackpackHint.SetActive(GreenHellGame.IsPadControllerActive() && !Inventory3DManager.Get().IsActive());
        this.m_SortBackpackHint.SetActive(GreenHellGame.IsPadControllerActive() && Inventory3DManager.Get().IsActive());
        Limb limb = Limb.None;

        if (GreenHellGame.IsPCControllerActive())
        {
            for (int i = 0; i < 4; i++)
            {
                if (this.m_SelectionColliders[i].OverlapPoint(Input.mousePosition))
                {
                    limb = (Limb)i;
                    break;
                }
            }
        }
        else if (!HUDItem.Get().enabled)
        {
            float   axis  = CrossPlatformInputManager.GetAxis("LeftStickX");
            float   axis2 = CrossPlatformInputManager.GetAxis("LeftStickY");
            Vector2 zero  = Vector2.zero;
            zero.x = axis;
            zero.y = axis2;
            if (zero.magnitude > 0.08f)
            {
                float num = Vector3.Angle(zero, Vector3.up);
                if (axis > 0f)
                {
                    num = 360f - num;
                }
                if (num <= 90f)
                {
                    limb = Limb.RArm;
                }
                else if (num > 90f && num <= 180f)
                {
                    limb = Limb.RLeg;
                }
                else if (num > 180f && num <= 270f)
                {
                    limb = Limb.LLeg;
                }
                else if (num > 270f)
                {
                    limb = Limb.LArm;
                }
            }
        }
        this.SelectLimb(limb);
        if ((GreenHellGame.IsPCControllerActive() && Input.GetMouseButtonDown(0)) || (GreenHellGame.IsPadControllerActive() && Input.GetKeyDown(InputHelpers.PadButton.L3.KeyFromPad())))
        {
            this.OnClickLimb(limb);
            switch (limb)
            {
            case Limb.LArm:
                BodyInspectionController.Get().m_Inputs.m_ChooseLimbX = -1f;
                BodyInspectionController.Get().m_Inputs.m_ChooseLimbY = 1f;
                break;

            case Limb.RArm:
                BodyInspectionController.Get().m_Inputs.m_ChooseLimbX = 1f;
                BodyInspectionController.Get().m_Inputs.m_ChooseLimbY = 1f;
                break;

            case Limb.LLeg:
                BodyInspectionController.Get().m_Inputs.m_ChooseLimbX = -1f;
                BodyInspectionController.Get().m_Inputs.m_ChooseLimbY = -1f;
                break;

            case Limb.RLeg:
                BodyInspectionController.Get().m_Inputs.m_ChooseLimbX = 1f;
                BodyInspectionController.Get().m_Inputs.m_ChooseLimbY = -1f;
                break;
            }
        }
        this.UpdateArmor();
        this.UpdateSmallIcons();
        this.UpdateArmorTooltip();
    }
Ejemplo n.º 9
0
 public LimbAdapter(Limb target)
 {
     _target = target;
 }
Ejemplo n.º 10
0
 private float CalculateDoubleStep (Limb cur, Limb prv, int distance_from_start) {
     if (IsJack(cur, prv)) {
         return 0.0f;
     }
     float cost = 0.0f;
     cost += DOUBLE_STEP_COST;
     cost += DOUBLE_STEP_COST_DELTA_PER_NODE * distance_from_start;
     return cost;
 }
Ejemplo n.º 11
0
 private float CalculateBracketAngle (
     float facing_deg, Vector avoid_bracket_dir_a, Vector avoid_bracket_dir_b,
     bool is_left, Limb limb
 ) {
     if (!limb.IsActiveBracket()) { return 0.0f; }
     Vector bracket_dir = Panel.GetBracketDirection(
         is_left,
         limb.main.IsUnknown() || limb.main.IsPassiveDown() ? -1 : limb.main.panel.index,
         limb.sub.IsUnknown() || limb.sub.IsPassiveDown() ? -1 : limb.sub.panel.index,
         limb.extra.IsUnknown() || limb.extra.IsPassiveDown() ? -1 : limb.extra.panel.index
     );
     if (facing_deg == 0.0f) {
         if (bracket_dir.dx == 1.0f && bracket_dir.dy == 0.0f) {
             return 0.0f;
         }
     } else if (facing_deg == 180.0f) {
         if (bracket_dir.dx == -1.0f && bracket_dir.dy == 0.0f) {
             return 0.0f;
         }
     }
     float alignment_a = (bracket_dir.dot(avoid_bracket_dir_a) + 1.0f) / 2.0f;
     float alignment_b = (bracket_dir.dot(avoid_bracket_dir_b) + 1.0f) / 2.0f;
     float alignment = alignment_a < alignment_b ?
         alignment_a : alignment_b;
     return BAD_BRACKET_DEGREE_COST * ExpInterpolate(alignment, BAD_BRACKET_DEGREE_EXP_CONST);
 }
Ejemplo n.º 12
0
 private static bool IsJack (Limb cur, Limb prv) {
     int cur_moved_count = 0;
     int prv_moved_count = 0;
     for (int i = 0; i < Limb.PART_COUNT; ++i) {
         if (cur[i].JustMoved() && !cur[i].IsUnknown()) {
             ++cur_moved_count;
         }
     }
     for (int i = 0; i < Limb.PART_COUNT; ++i) {
         if (prv[i].JustMoved() && !prv[i].IsUnknown()) {
             ++prv_moved_count;
         }
     }
     bool is_jack = false;
     if (cur_moved_count >= prv_moved_count) {
         int matches = 0;
         for (int i = 0; i < Limb.PART_COUNT; ++i) {
             if (!prv[i].JustMoved() || prv[i].IsUnknown()) {
                 continue;
             }
             bool is_currently_occupied = false;
             for (int j = 0; j < Limb.PART_COUNT; ++j) {
                 if (cur[j].JustMoved() && !cur[j].IsUnknown()) {
                     //I can just compare panel instances but I'm too paranoid about null-ref errors
                     if (prv[i].panel.index == cur[j].panel.index) {
                         is_currently_occupied = true;
                     }
                 }
             }
             if (is_currently_occupied) {
                 ++matches;
             } else {
                 break;
             }
         }
         if (matches == prv_moved_count) {
             is_jack = true;
         }
     }
     return is_jack;
 }
Ejemplo n.º 13
0
 private static bool IsJustBracket (Limb[] limbs) {
     foreach (Limb limb in limbs) {
         int moved = 0;
         for (int p = 0; p < Limb.PART_COUNT; ++p) {
             Part part = limb[p];
             if (part.JustMoved() && !part.IsUnknown() && !part.IsPassiveDown()) {
                 ++moved;
             }
         }
         if (moved >= 2) {
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 14
0
            private bool IsGallop (
                Limb cur, Limb prv,
                Beat cur_beat, Beat prv_beat
            ) {
                if (
                    cur_beat.beat_interval < GALLOP_BEAT_INTERVAL ||
                    prv_beat.beat_interval < GALLOP_BEAT_INTERVAL
                ) {
                    return false; //Consider making it.. 24?
                }
                float delta_second = cur_beat.second - prv_beat.second;
                if (delta_second > cur_beat.seconds_per_beat / GALLOP_BEATS_PER_MEASURE + GALLOP_SECONDS_EPOCH) {
                    return false; //Unsure if this is correct..
                }
                if (cur.JustMovedCount() != 1 || prv.JustMovedCount() != 1) {
                    return false; //For now, gallops are two taps..
                }
                int cur_just_moved_index = cur.JustMovedIndex();
                int prv_just_moved_index = prv.JustMovedIndex();
                if (cur_just_moved_index == prv_just_moved_index) {
                    return false; //.. by different parts of the same limb
                }

                Part cur_part = cur[cur_just_moved_index];
                Part prv_part = prv[prv_just_moved_index];
                if (cur_part.panel == null || prv_part.panel == null) {
                    return false; //Must be hitting a note
                }
                if (cur_part.panel == prv_part.panel) {
                    return false; //Must hit different notes
                }
                if (!Panel.IsBracketable(
                    cur_part.panel.index, prv_part.panel.index
                )) {
                    return false; //Must be bracketable
                }
                return true;
            }
Ejemplo n.º 15
0
 public MovementLimbKey(Movement m, Limb l)
 {
     movement = m;
     limb = l;
 }
Ejemplo n.º 16
0
        //Green text. Function here.
        public Player(ContentManager sCont, gridCoordinate sGridCoord, ref List<string> msgBuffer, 
                      Chara_Class myClass, Character myChara, ref PaperDoll pd)
        {
            //Constructor stuff
            cont = sCont;
            my_grid_coord = new gridCoordinate(sGridCoord);
            my_Position = new Vector2(sGridCoord.x * 32, sGridCoord.y * 32);
            rGen = new Random();
            message_buffer = msgBuffer;
            //!Constructor stuff
            my_gold = 0;
            base_smell_value = 10;
            base_sound_value = 10;
            //Player stuff
            my_class = myClass;
            my_character = myChara;
            base_hp = 3;
            if (my_character == Character.Belia)
                base_hp++; //Belia gets +60 HP to all of her body parts.

            switch (my_character)
            {
                case Character.Falsael:
                    my_Texture = cont.Load<Texture2D>("Player/falsael_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/falsael_dead");
                    break;
                case Character.Petaer:
                    my_Texture = cont.Load<Texture2D>("Player/petaer_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/petaer_dead");
                    break;
                case Character.Ziktofel:
                    my_Texture = cont.Load<Texture2D>("Player/ziktofel_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/ziktofel_dead");
                    break;
                case Character.Halephon:
                    my_Texture = cont.Load<Texture2D>("Player/halephon_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/halephon_dead");
                    break;
                case Character.Belia:
                    my_Texture = cont.Load<Texture2D>("Player/belia_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/belia_sprite");
                    break;
                default:
                    my_Texture = cont.Load<Texture2D>("Player/lmfaoplayer");
                    my_dead_texture = cont.Load<Texture2D>("Player/playercorpse");
                    break;
            }
            //Health stuff.
            Head = new Limb(ref rGen, "Head", "Head", base_hp - 2);
            Torso = new Limb(ref rGen, "Chest", "Chest", base_hp);
            R_Arm = new Limb(ref rGen, "Right Arm", "RArm", base_hp);
            L_Arm = new Limb(ref rGen, "Left Arm", "LArm", base_hp);
            R_Leg = new Limb(ref rGen, "Right Leg", "RLeg", base_hp);
            L_Leg = new Limb(ref rGen, "Left Leg", "LLeg", base_hp);
            calculate_dodge_chance();
            //Inventory stuff
            inventory = new List<Item>();
            reserved_potion_ids = new List<Tuple<int, int>>();
            for(int i = 1; i <= 3; i++)
                reserved_potion_ids.Add(new Tuple<int,int>(i, new_random_ID_number()));

            add_starting_gear();
            //Character stuff
            BuffDebuffTracker = new List<StatusEffect>();

            pDoll = pd;

            normal_backing = Color.White;
            invis_backing = new Color(255, 255, 255, 75);
        }
Ejemplo n.º 17
0
 public Exercise(Movement m, Limb l)
 {
     this.movement = m;
     this.limb = l;
 }
Ejemplo n.º 18
0
 private float CalculateTooFast (
     Limb cur, Limb prv,
     Beat cur_beat, Beat prv_beat
 ) {
     if (IsGallop(cur, prv, cur_beat, prv_beat)) {
         return 0.0f;
     }
     if (
         cur_beat.beat_interval < GALLOP_BEAT_INTERVAL ||
         prv_beat.beat_interval < GALLOP_BEAT_INTERVAL
     ) {
         return 0.0f; //Consider making it.. 24?
     }
     float delta_second = cur_beat.second - prv_beat.second;
     if (
         delta_second > (cur_beat.seconds_per_beat / GALLOP_BEATS_PER_MEASURE + GALLOP_SECONDS_EPOCH) * 2.0f) {
         return 0.0f; //Unsure if this is correct..
     }
     List<int> cur_indices = cur.JustMovedIndices();
     List<int> prv_indices = prv.JustMovedIndices();
     if (cur_indices.Count == 0 || prv_indices.Count == 0) {
         return 0.0f;
     }
     float cost = 0.0f;
     for (int c = 0; c < cur_indices.Count; ++c) {
         int cur_index = cur_indices[c];
         Part cur_part = cur[cur_index];
         for (int p = 0; p < prv_indices.Count; ++p) {
             int prv_index = prv_indices[p];
             Part prv_part = prv[prv_index];
             if (cur_part.IsUnknown() || prv_part.IsUnknown()) { continue; }
             if (cur_index == prv_index) {
                 if (cur_part.panel == prv_part.panel) {
                     //Do nothing?
                 } else {
                     cost += TOO_FAST_COST;
                 }
             } else {
                 if (cur_part.panel == prv_part.panel) {
                     //Different parts but same panel, a.. part switch?
                     cost += TOO_FAST_COST;//For now, treat it as too fast
                 } else if (Panel.IsBracketable(cur_part.panel.index, prv_part.panel.index)) {
                     //Do nothing, it's a gallop-ish thing
                 } else {
                     //Too fast, probably
                     cost += TOO_FAST_COST;
                 }
             }
         }
     }
     return cost;
 }
Ejemplo n.º 19
0
    public override void OnTakeDamage(DamageInfo info)
    {
        base.OnTakeDamage(info);
        if (info.m_Blocked)
        {
            return;
        }
        float num = info.m_Damage;

        info.m_InjuryPlace = this.GetInjuryPlaceFromHit(info);
        if (!info.m_FromInjury)
        {
            Limb limb = EnumTools.ConvertInjuryPlaceToLimb(info.m_InjuryPlace);
            if (limb == Limb.None)
            {
                limb = Limb.LArm;
            }
            if (info.m_DamageType != DamageType.Fall && info.m_DamageType != DamageType.SnakePoison && info.m_DamageType != DamageType.VenomPoison && info.m_DamageType != DamageType.Insects && info.m_DamageType != DamageType.Infection)
            {
                num = info.m_Damage * (1f - PlayerArmorModule.Get().GetAbsorption(limb));
            }
            PlayerArmorModule.Get().SetPhaseCompleted(ArmorTakeDamagePhase.InjuryModule);
        }
        float num2 = 5f;

        if ((num > num2 && PlayerArmorModule.Get().NoArmorAfterDamage(info)) || info.m_DamageType == DamageType.Insects || info.m_DamageType == DamageType.SnakePoison || info.m_DamageType == DamageType.VenomPoison || info.m_DamageType == DamageType.Fall || info.m_DamageType == DamageType.Infection)
        {
            BIWoundSlot biwoundSlot = null;
            DamageType  damageType  = info.m_DamageType;
            InjuryType  injuryType;
            if (damageType <= DamageType.Claws)
            {
                if (damageType <= DamageType.Melee)
                {
                    if (damageType - DamageType.Cut > 1)
                    {
                        if (damageType == DamageType.Melee)
                        {
                            injuryType = InjuryType.SmallWoundAbrassion;
                            goto IL_17F;
                        }
                    }
                    else
                    {
                        if (info.m_CriticalHit)
                        {
                            injuryType = InjuryType.Laceration;
                            goto IL_17F;
                        }
                        injuryType = InjuryType.SmallWoundScratch;
                        goto IL_17F;
                    }
                }
                else
                {
                    if (damageType == DamageType.VenomPoison)
                    {
                        injuryType = InjuryType.VenomBite;
                        goto IL_17F;
                    }
                    if (damageType == DamageType.Claws)
                    {
                        injuryType = InjuryType.LacerationCat;
                        goto IL_17F;
                    }
                }
            }
            else if (damageType <= DamageType.Fall)
            {
                if (damageType == DamageType.Insects)
                {
                    injuryType = InjuryType.Rash;
                    goto IL_17F;
                }
                if (damageType == DamageType.Fall)
                {
                    injuryType = InjuryType.SmallWoundAbrassion;
                    goto IL_17F;
                }
            }
            else
            {
                if (damageType == DamageType.Critical)
                {
                    injuryType = InjuryType.Laceration;
                    goto IL_17F;
                }
                if (damageType == DamageType.SnakePoison)
                {
                    injuryType = InjuryType.SnakeBite;
                    goto IL_17F;
                }
            }
            injuryType = InjuryType.SmallWoundAbrassion;
IL_17F:
            if (!info.m_FromInjury && (injuryType == InjuryType.VenomBite || injuryType == InjuryType.SnakeBite))
            {
                Disease disease = PlayerDiseasesModule.Get().GetDisease(ConsumeEffect.Fever);
                if (disease != null && disease.IsActive())
                {
                    disease.IncreaseLevel(1);
                }
                else
                {
                    PlayerDiseasesModule.Get().RequestDisease(ConsumeEffect.Fever, 0f, 1);
                }
            }
            if (info.m_DamageType == DamageType.Insects && GreenHellGame.TWITCH_DEMO)
            {
                biwoundSlot = this.m_BodyInspectionController.GetFreeWoundSlot(InjuryPlace.LHand, injuryType, true);
            }
            else if (info.m_InjuryPlace == InjuryPlace.LLeg)
            {
                biwoundSlot = this.m_BodyInspectionController.GetFreeWoundSlot(InjuryPlace.LLeg, injuryType, true);
            }
            else if (info.m_InjuryPlace == InjuryPlace.RLeg)
            {
                biwoundSlot = this.m_BodyInspectionController.GetFreeWoundSlot(InjuryPlace.RLeg, injuryType, true);
            }
            else if (info.m_InjuryPlace == InjuryPlace.LHand)
            {
                biwoundSlot = this.m_BodyInspectionController.GetFreeWoundSlot(InjuryPlace.LHand, injuryType, true);
            }
            else if (info.m_InjuryPlace == InjuryPlace.RHand)
            {
                biwoundSlot = this.m_BodyInspectionController.GetFreeWoundSlot(InjuryPlace.RHand, injuryType, true);
            }
            if (biwoundSlot != null)
            {
                InjuryState state = InjuryState.Open;
                if (injuryType == InjuryType.Laceration || injuryType == InjuryType.LacerationCat)
                {
                    state = InjuryState.Bleeding;
                }
                else if (injuryType == InjuryType.WormHole)
                {
                    state = InjuryState.WormInside;
                }
                this.AddInjury(injuryType, biwoundSlot.m_InjuryPlace, biwoundSlot, state, info.m_PoisonLevel, null, info);
                return;
            }
            if (info.m_DamageType == DamageType.VenomPoison)
            {
                for (int i = 0; i < this.m_Injuries.Count; i++)
                {
                    if (this.m_Injuries[i].m_Type == InjuryType.VenomBite)
                    {
                        this.m_Injuries[i].m_PoisonLevel += info.m_PoisonLevel;
                        return;
                    }
                }
                return;
            }
            if (info.m_DamageType == DamageType.SnakePoison)
            {
                for (int j = 0; j < this.m_Injuries.Count; j++)
                {
                    if (this.m_Injuries[j].m_Type == InjuryType.SnakeBite)
                    {
                        this.m_Injuries[j].m_PoisonLevel += info.m_PoisonLevel;
                        return;
                    }
                }
            }
        }
    }
Ejemplo n.º 20
0
        public void ApplyStatusEffects(ActionType type, float deltaTime, Character character = null, Limb targetLimb = null, Entity useTarget = null, Character user = null, Vector2?worldPosition = null)
        {
            if (statusEffectLists == null)
            {
                return;
            }

            if (!statusEffectLists.TryGetValue(type, out List <StatusEffect> statusEffects))
            {
                return;
            }

            bool broken           = item.Condition <= 0.0f;
            bool reducesCondition = false;

            foreach (StatusEffect effect in statusEffects)
            {
                if (broken && !effect.AllowWhenBroken && effect.type != ActionType.OnBroken)
                {
                    continue;
                }
                if (user != null)
                {
                    effect.SetUser(user);
                }
                item.ApplyStatusEffect(effect, type, deltaTime, character, targetLimb, useTarget, false, false, worldPosition);
                reducesCondition |= effect.ReducesItemCondition();
            }
            //if any of the effects reduce the item's condition, set the user for OnBroken effects as well
            if (reducesCondition && user != null && type != ActionType.OnBroken)
            {
                foreach (ItemComponent ic in item.Components)
                {
                    if (ic.statusEffectLists == null || !ic.statusEffectLists.TryGetValue(ActionType.OnBroken, out List <StatusEffect> brokenEffects))
                    {
                        continue;
                    }
                    brokenEffects.ForEach(e => e.SetUser(user));
                }
            }

#if CLIENT
            HintManager.OnStatusEffectApplied(this, type, character);
#endif
        }
 partial void UpdateProjSpecific(CharacterHealth characterHealth, Limb targetLimb, float deltaTime);
Ejemplo n.º 22
0
 /// <summary>
 /// Obtiene todos los behaviours que calcen con el movement
 /// </summary>
 /// <param name="movement"></param>
 public static AnimationBehaviour GetCentralBehaviour(Movement movement, Limb limb)
 {
     int mov = (int)movement / MAGIC_NUMBER;
     Animator a = GameObject.FindObjectOfType<AnimatorScript>().anim;
     AnimationBehaviour[] behaviours = a.GetBehaviours<AnimationBehaviour>();
     List<AnimationBehaviour> centrals = new List<AnimationBehaviour>();
     foreach (AnimationBehaviour lb in behaviours)
     {
         int m = (int)lb.movement / MAGIC_NUMBER;
         if (m == mov)
         {
             if (lb.animator == null)
             {
                 lb.animator = a;
             }
             if (lb.IsCentralNode)
             {
                 centrals.Add(lb);
             }
         }
     }
     foreach (AnimationBehaviour lb in centrals)
     {
         if (lb.limb == limb)
             return lb;
     }
     return null;
     
 }
Ejemplo n.º 23
0
        private bool OnCollision(Fixture f1, Fixture f2, Contact contact)
        {
            Character targetCharacter = null;
            Limb      targetLimb      = null;
            Structure targetStructure = null;

            if (f2.Body.UserData is Limb)
            {
                targetLimb = (Limb)f2.Body.UserData;
                if (targetLimb.IsSevered || targetLimb.character == null)
                {
                    return(false);
                }
                targetCharacter = targetLimb.character;
            }
            else if (f2.Body.UserData is Character)
            {
                targetCharacter = (Character)f2.Body.UserData;
                targetLimb      = targetCharacter.AnimController.GetLimb(LimbType.Torso); //Otherwise armor can be bypassed in strange ways
            }
            else if (f2.Body.UserData is Structure)
            {
                targetStructure = (Structure)f2.Body.UserData;
            }
            else
            {
                return(false);
            }

            if (targetCharacter == picker)
            {
                return(false);
            }

            if (attack != null)
            {
                if (targetLimb != null)
                {
                    attack.DoDamageToLimb(user, targetLimb, item.WorldPosition, 1.0f);
                }
                else if (targetCharacter != null)
                {
                    attack.DoDamage(user, targetCharacter, item.WorldPosition, 1.0f);
                }
                else if (targetStructure != null)
                {
                    attack.DoDamage(user, targetStructure, item.WorldPosition, 1.0f);
                }
                else
                {
                    return(false);
                }
            }

            RestoreCollision();
            hitting = false;

            if (GameMain.Client != null)
            {
                return(true);
            }

            if (GameMain.Server != null && targetCharacter != null) //TODO: Log structure hits
            {
                GameMain.Server.CreateEntityEvent(item, new object[] { Networking.NetEntityEvent.Type.ApplyStatusEffect, ActionType.OnUse, targetCharacter.ID });

                string logStr = picker?.LogName + " used " + item.Name;
                if (item.ContainedItems != null && item.ContainedItems.Length > 0)
                {
                    logStr += "(" + string.Join(", ", item.ContainedItems.Select(i => i?.Name)) + ")";
                }
                logStr += " on " + targetCharacter.LogName + ".";
                Networking.GameServer.Log(logStr, Networking.ServerLog.MessageType.Attack);
            }

            if (targetCharacter != null) //TODO: Allow OnUse to happen on structures too maybe??
            {
                ApplyStatusEffects(ActionType.OnUse, 1.0f, targetCharacter != null ? targetCharacter : null);
            }

            return(true);
        }
Ejemplo n.º 24
0
        public Player(ContentManager sCont, ref List<string> msgBuffer, ref PaperDoll pd, PlayerDC raw_player)
        {
            //Constructor stuff
            cont = sCont;
            my_grid_coord = new gridCoordinate(raw_player.Player_GC_X, raw_player.Player_GC_Y);
            my_Position = new Vector2(raw_player.Player_GC_X * 32, raw_player.Player_GC_Y * 32);
            rGen = new Random();
            message_buffer = msgBuffer;
            //!Constructor stuff
            my_gold = raw_player.Player_Gold;
            lifetime_gold = raw_player.Player_Lifetime_Gold;
            base_smell_value = 10;
            base_sound_value = 10;
            //Player stuff
            my_class = ((Chara_Class)Enum.Parse(typeof(Chara_Class), raw_player.Chara_Class));
            my_character = ((Character)Enum.Parse(typeof(Character), raw_player.Character));

            switch (my_character)
            {
                case Character.Falsael:
                    my_Texture = cont.Load<Texture2D>("Player/falsael_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/falsael_dead");
                    break;
                case Character.Petaer:
                    my_Texture = cont.Load<Texture2D>("Player/petaer_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/petaer_dead");
                    break;
                case Character.Ziktofel:
                    my_Texture = cont.Load<Texture2D>("Player/ziktofel_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/ziktofel_dead");
                    break;
                case Character.Halephon:
                    my_Texture = cont.Load<Texture2D>("Player/halephon_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/halephon_dead");
                    break;
                case Character.Belia:
                    my_Texture = cont.Load<Texture2D>("Player/belia_sprite");
                    my_dead_texture = cont.Load<Texture2D>("Player/belia_sprite");
                    break;
                default:
                    my_Texture = cont.Load<Texture2D>("Player/lmfaoplayer");
                    my_dead_texture = cont.Load<Texture2D>("Player/playercorpse");
                    break;
            }
            //Health stuff.
            base_hp = raw_player.Base_Health;

            BuffDebuffTracker = new List<StatusEffect>();

            Head = new Limb(raw_player.Limbs[0]);
            Torso = new Limb(raw_player.Limbs[1]);
            R_Arm = new Limb(raw_player.Limbs[2]);
            L_Arm = new Limb(raw_player.Limbs[3]);
            R_Leg = new Limb(raw_player.Limbs[4]);
            L_Leg = new Limb(raw_player.Limbs[5]);
            //Inventory stuff
            inventory = new List<Item>();

            reserved_potion_ids = new List<Tuple<int, int>>(); //WILL NEED TO FIGURE THESE OUT.
            for (int i = 0; i < raw_player.Reserved_Potion_Code.Count; i++)
                reserved_potion_ids.Add(new Tuple<int, int>(raw_player.Reserved_Potion_Code[i], raw_player.Reserved_Potion_ID[i]));

            for (int i = 0; i < raw_player.Armors_In_Inv.Count; i++)
                inventory.Add(new Armor(raw_player.Armors_In_Inv[i]));

            for (int i = 0; i < raw_player.Potions_In_Inv.Count; i++)
                acquire_potion(new Potion(raw_player.Potions_In_Inv[i]));

            for (int i = 0; i < raw_player.Scrolls_In_Inv.Count; i++)
                inventory.Add(new Scroll(raw_player.Scrolls_In_Inv[i]));

            for (int i = 0; i < raw_player.Weapons_In_Inv.Count; i++)
                inventory.Add(new Weapon(raw_player.Weapons_In_Inv[i]));

            //Equipped Items
            Weapon next_mh = null;
            if (raw_player.Main_Hand != null)
            {
                next_mh = new Weapon(raw_player.Main_Hand);
                equip_main_hand(next_mh);
            }
            Weapon next_oh = null;
            if (raw_player.Off_Hand != null)
            {
                next_oh = new Weapon(raw_player.Off_Hand);
                equip_off_hand(next_oh);
            }
            Armor next_helmet = null;
            if (raw_player.Helmet != null)
            {
                next_helmet = new Armor(raw_player.Helmet);
                equip_armor(next_helmet);
            }
            Armor next_OA = null;
            if (raw_player.Over_Armor != null)
            {
                next_OA = new Armor(raw_player.Over_Armor);
                equip_armor(next_OA);
            }
            Armor next_UA = null;
            if (raw_player.Under_Armor != null)
            {
                next_UA = new Armor(raw_player.Under_Armor);
                equip_armor(next_UA);
            }

            //Character stuff
            base_smell_value = raw_player.Player_Base_Smell;
            base_sound_value = raw_player.Player_Base_Sound;

            c_energy = raw_player.Player_Current_Energy;
            max_energy = raw_player.Player_Max_Energy;

            calculate_dodge_chance();

            pDoll = pd;

            normal_backing = Color.White;
            invis_backing = new Color(255, 255, 255, 75);
        }
Ejemplo n.º 25
0
 public void ReadPortable(IPortableReader reader)
 {
     name = reader.ReadUTF("name");
     limb = reader.ReadPortable <Limb>("limb");
 }
Ejemplo n.º 26
0
 //Should be called when a limb runs out of life, to avoid losing references
 public virtual void LimbDestroyed(Limb limb)
 {
     _limbs.Remove(limb);
     Destroy(limb.gameObject);
 }
Ejemplo n.º 27
0
				bool _SolveLimbTranslate( Limb limb, out Vector3 origTranslate )
				{
					origTranslate = Vector3.zero;

					float lerpRate = (limb == arms) ? _solverCaches.limbArmRate : _solverCaches.limbLegRate;

					if( limb.targetBeginPosEnabled[0] && limb.targetBeginPosEnabled[1] ) {
						origTranslate = Vector3.Lerp( this.origTranslate[0], this.origTranslate[1], lerpRate );
					} else if( limb.targetBeginPosEnabled[0] || limb.targetBeginPosEnabled[1] ) {
						int i0 = limb.targetBeginPosEnabled[0] ? 0 : 1;
						float lerpRate1to0 = limb.targetBeginPosEnabled[0] ? (1.0f - lerpRate) : lerpRate;
						origTranslate = this.origTranslate[i0] * lerpRate1to0;
					}

					return (origTranslate != Vector3.zero);
				}
        private void HandleImpact(Body target)
        {
            if (User == null || User.Removed || target == null)
            {
                RestoreCollision();
                hitting = false;
                User    = null;
                return;
            }

            Limb      targetLimb      = target.UserData as Limb;
            Character targetCharacter = targetLimb?.character ?? target.UserData as Character;
            Structure targetStructure = target.UserData as Structure;
            Item      targetItem      = target.UserData as Item;

            if (Attack != null)
            {
                Attack.SetUser(User);

                if (targetLimb != null)
                {
                    if (targetLimb.character.Removed)
                    {
                        return;
                    }
                    targetLimb.character.LastDamageSource = item;
                    Attack.DoDamageToLimb(User, targetLimb, item.WorldPosition, 1.0f);
                }
                else if (targetCharacter != null)
                {
                    if (targetCharacter.Removed)
                    {
                        return;
                    }
                    targetCharacter.LastDamageSource = item;
                    Attack.DoDamage(User, targetCharacter, item.WorldPosition, 1.0f);
                }
                else if (targetStructure != null)
                {
                    if (targetStructure.Removed)
                    {
                        return;
                    }
                    Attack.DoDamage(User, targetStructure, item.WorldPosition, 1.0f);
                }
                else if (targetItem != null && targetItem.Prefab.DamagedByMeleeWeapons && targetItem.Condition > 0)
                {
                    if (targetItem.Removed)
                    {
                        return;
                    }
                    Attack.DoDamage(User, targetItem, item.WorldPosition, 1.0f);
                }
                else
                {
                    return;
                }
            }

            if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
            {
                return;
            }

            bool success = Rand.Range(0.0f, 0.5f) < DegreeOfSuccess(User);

#if SERVER
            if (GameMain.Server != null && targetCharacter != null) //TODO: Log structure hits
            {
                GameMain.Server.CreateEntityEvent(item, new object[]
                {
                    Networking.NetEntityEvent.Type.ApplyStatusEffect,
                    success ? ActionType.OnUse : ActionType.OnFailure,
                    null, //itemcomponent
                    targetCharacter.ID, targetLimb
                });

                string logStr = picker?.LogName + " used " + item.Name;
                if (item.ContainedItems != null && item.ContainedItems.Any())
                {
                    logStr += " (" + string.Join(", ", item.ContainedItems.Select(i => i?.Name)) + ")";
                }
                logStr += " on " + targetCharacter.LogName + ".";
                Networking.GameServer.Log(logStr, Networking.ServerLog.MessageType.Attack);
            }
#endif

            if (targetCharacter != null) //TODO: Allow OnUse to happen on structures too maybe??
            {
                ApplyStatusEffects(success ? ActionType.OnUse : ActionType.OnFailure, 1.0f, targetCharacter, targetLimb, user: User);
            }

            if (DeleteOnUse)
            {
                Entity.Spawner.AddToRemoveQueue(item);
            }
        }
Ejemplo n.º 29
0
        public void ApplyStatusEffects(ActionType type, float deltaTime, Character character = null, Limb targetLimb = null, Character user = null)
        {
            if (statusEffectLists == null)
            {
                return;
            }

            if (!statusEffectLists.TryGetValue(type, out List <StatusEffect> statusEffects))
            {
                return;
            }

            bool broken = item.Condition <= 0.0f;

            foreach (StatusEffect effect in statusEffects)
            {
                if (broken && effect.type != ActionType.OnBroken)
                {
                    continue;
                }
                if (user != null)
                {
                    effect.SetUser(user);
                }
                item.ApplyStatusEffect(effect, type, deltaTime, character, targetLimb, false, false);
            }
        }
Ejemplo n.º 30
0
 public static bool Equal(InjuryPlace place, Limb limb)
 {
     return((place == InjuryPlace.LHand && limb == Limb.LArm) || (place == InjuryPlace.RHand && limb == Limb.RArm) || (place == InjuryPlace.LLeg && limb == Limb.LLeg) || (place == InjuryPlace.RLeg && limb == Limb.RLeg));
 }
Ejemplo n.º 31
0
        public override void Update(float deltaTime, Camera cam)
        {
            if (!item.body.Enabled)
            {
                return;
            }
            if (picker == null || picker.Removed || !picker.HasSelectedItem(item))
            {
                IsActive = false;
                return;
            }

            if (picker.IsKeyDown(InputType.Aim) && picker.IsKeyHit(InputType.Use))
            {
                throwing = true;
            }

            if (!picker.IsKeyDown(InputType.Aim) && !throwing)
            {
                throwPos = 0.0f;
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);

            if (item.body.Dir != picker.AnimController.Dir)
            {
                Flip(item);
            }

            AnimController ac = picker.AnimController;

            item.Submarine = picker.Submarine;

            if (!throwing)
            {
                if (picker.IsKeyDown(InputType.Aim))
                {
                    throwPos = (float)System.Math.Min(throwPos + deltaTime * 5.0f, MathHelper.Pi * 0.7f);

                    ac.HoldItem(deltaTime, item, handlePos, new Vector2(0.6f, -0.0f), new Vector2(-0.3f, 0.2f), false, throwPos);
                }
                else
                {
                    ac.HoldItem(deltaTime, item, handlePos, holdPos, aimPos, false, holdAngle);
                }
            }
            else
            {
                throwPos -= deltaTime * 15.0f;

                ac.HoldItem(deltaTime, item, handlePos, new Vector2(0.6f, 0.0f), new Vector2(-0.3f, 0.2f), false, throwPos);

                if (throwPos < -0.0)
                {
                    Vector2 throwVector = Vector2.Normalize(picker.CursorWorldPosition - picker.WorldPosition);
                    //throw upwards if cursor is at the position of the character
                    if (!MathUtils.IsValid(throwVector))
                    {
                        throwVector = Vector2.UnitY;
                    }

                    GameServer.Log(picker.LogName + " threw " + item.Name, ServerLog.MessageType.ItemInteraction);

                    if (GameMain.NilMod.EnableGriefWatcher)
                    {
                        //Grief watch throw checks
                        for (int y = 0; y < NilMod.NilModGriefWatcher.GWListThrown.Count; y++)
                        {
                            if (NilMod.NilModGriefWatcher.GWListThrown[y] == Item.Name)
                            {
                                Barotrauma.Networking.Client warnedclient = GameMain.Server.ConnectedClients.Find(c => c.Character == picker);

                                if (item.ContainedItems == null || item.ContainedItems.All(it => it == null))
                                {
                                    NilMod.NilModGriefWatcher.SendWarning(picker.LogName
                                                                          + " threw dangerous item " + Item.Name, warnedclient);
                                }
                                else
                                {
                                    NilMod.NilModGriefWatcher.SendWarning(picker.LogName
                                                                          + " threw dangerous item "
                                                                          + Item.Name
                                                                          + " (" + string.Join(", ", System.Array.FindAll(item.ContainedItems, it => it != null).Select(it => it.Name))
                                                                          + ")", warnedclient);
                                }
                            }
                        }
                    }

                    item.Drop();
                    item.body.ApplyLinearImpulse(throwVector * throwForce * item.body.Mass * 3.0f);

                    ac.GetLimb(LimbType.Head).body.ApplyLinearImpulse(throwVector * 10.0f);
                    ac.GetLimb(LimbType.Torso).body.ApplyLinearImpulse(throwVector * 10.0f);

                    Limb rightHand = ac.GetLimb(LimbType.RightHand);
                    item.body.AngularVelocity = rightHand.body.AngularVelocity;
                    throwDone = true;
                    ApplyStatusEffects(ActionType.OnSecondaryUse, deltaTime, picker); //Stun grenades, flares, etc. all have their throw-related things handled in "onSecondaryUse"
                    throwing = false;
                }
            }
        }
Ejemplo n.º 32
0
        void SetupLimb(Blob bodyPart, Limb.LimbComponentType type, Limb.LimbPosition position)
        {
            Limb visual = new Limb(type, position, randomDepth);

            bodyPart.AddComponent(visual);
        }
Ejemplo n.º 33
0
        public override void Update(float deltaTime, Camera cam)
        {
            this.cam = cam;

            if (IsToggle)
            {
                item.SendSignal(0, State ? "1" : "0", "signal_out", sender: null);
            }

            if (user == null ||
                user.Removed ||
                user.SelectedConstruction != item ||
                item.ParentInventory != null ||
                !user.CanInteractWith(item) ||
                (UsableIn == UseEnvironment.Water && !user.AnimController.InWater) ||
                (UsableIn == UseEnvironment.Air && user.AnimController.InWater))
            {
                if (user != null)
                {
                    CancelUsing(user);
                    user = null;
                }
                if (!IsToggle)
                {
                    IsActive = false;
                }
                return;
            }

            user.AnimController.Anim = AnimController.Animation.UsingConstruction;

            if (userPos != Vector2.Zero)
            {
                Vector2 diff = (item.WorldPosition + userPos) - user.WorldPosition;

                if (user.AnimController.InWater)
                {
                    if (diff.LengthSquared() > 30.0f * 30.0f)
                    {
                        user.AnimController.TargetMovement = Vector2.Clamp(diff * 0.01f, -Vector2.One, Vector2.One);
                        user.AnimController.TargetDir      = diff.X > 0.0f ? Direction.Right : Direction.Left;
                    }
                    else
                    {
                        user.AnimController.TargetMovement = Vector2.Zero;
                    }
                }
                else
                {
                    diff.Y = 0.0f;
                    if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient && user != Character.Controlled)
                    {
                        if (Math.Abs(diff.X) > 20.0f)
                        {
                            //wait for the character to walk to the correct position
                            return;
                        }
                        else if (Math.Abs(diff.X) > 0.1f)
                        {
                            //aim to keep the collider at the correct position once close enough
                            user.AnimController.Collider.LinearVelocity = new Vector2(
                                diff.X * 0.1f,
                                user.AnimController.Collider.LinearVelocity.Y);
                        }
                    }
                    else
                    {
                        if (Math.Abs(diff.X) > 10.0f)
                        {
                            user.AnimController.TargetMovement = Vector2.Normalize(diff);
                            user.AnimController.TargetDir      = diff.X > 0.0f ? Direction.Right : Direction.Left;
                            return;
                        }
                    }
                    user.AnimController.TargetMovement = Vector2.Zero;
                }
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, user);

            if (limbPositions.Count == 0)
            {
                return;
            }

            user.AnimController.Anim = AnimController.Animation.UsingConstruction;

            user.AnimController.ResetPullJoints();

            if (dir != 0)
            {
                user.AnimController.TargetDir = dir;
            }

            foreach (LimbPos lb in limbPositions)
            {
                Limb limb = user.AnimController.GetLimb(lb.LimbType);
                if (limb == null || !limb.body.Enabled)
                {
                    continue;
                }

                if (lb.AllowUsingLimb)
                {
                    switch (lb.LimbType)
                    {
                    case LimbType.RightHand:
                    case LimbType.RightForearm:
                    case LimbType.RightArm:
                        if (user.SelectedItems[0] != null)
                        {
                            continue;
                        }
                        break;

                    case LimbType.LeftHand:
                    case LimbType.LeftForearm:
                    case LimbType.LeftArm:
                        if (user.SelectedItems[1] != null)
                        {
                            continue;
                        }
                        break;
                    }
                }

                limb.Disabled = true;

                Vector2 worldPosition = new Vector2(item.WorldRect.X, item.WorldRect.Y) + lb.Position * item.Scale;
                Vector2 diff          = worldPosition - limb.WorldPosition;

                limb.PullJointEnabled      = true;
                limb.PullJointWorldAnchorB = limb.SimPosition + ConvertUnits.ToSimUnits(diff);
            }
        }
Ejemplo n.º 34
0
    public void DetachLimb(Limb limb)
    {
        if (!isEquipmentDetached)
        {
            equipment.GetComponent <Rigidbody2D>().bodyType      = RigidbodyType2D.Dynamic;
            equipment.GetComponent <CapsuleCollider2D>().enabled = true;
            if (spriteToToggleOnOnEquipmentLost != null)
            {
                spriteToToggleOnOnEquipmentLost.enabled = true;
            }
            isEquipmentDetached = true;
            return;
        }
        //spawn blood particles and child them to the connected rigidbody of the joint at the joints position;
        Instantiate(bloodParticlesPrefab, limb.parentJoint.transform.position, Quaternion.identity, limb.parentJoint.connectedBody.transform);

        //detach by deactivating hingejoint
        limb.parentJoint.enabled = false;



        if (limb.name.Equals("RLeg")) // No more legs
        {
            giveUpCanvas.gameObject.SetActive(true);


            movement.StartTorsoMovement();
        }
        else if (limb.name.Equals("LArm"))
        {
            if (!GameManager.LivingSwordsMode())
            {
                movement.SwordMovement = false;
            }
        }
        else if (limb.name.Equals("Head"))
        {
            if (!hasDetachedHead)
            {
                movement.StartHeadMovement();

                //set the head's rigidbodys freeze y position to false
                limb.parentJoint.gameObject.GetComponent <Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
                //set the body's (the limbs connected rigidbody) rigidbodys freeze y position to false
                limb.parentJoint.connectedBody.constraints = RigidbodyConstraints2D.None;
                limb.parentJoint.connectedBody.tag         = "Untagged";
                limb.parentJoint.connectedBody.mass        = 0.5f;

                //Change movement to affect the head
                gameObject.GetComponent <Movement>().PhysicsBody = limb.parentJoint.gameObject.GetComponent <Rigidbody2D>();
                hasDetachedHead = true;
            }
            return;
        }


        foreach (var l in limb.parentJoint.GetComponentsInChildren <Rigidbody2D>())
        {
            l.tag  = "Untagged";
            l.mass = 0.5f;
        }

        //remove the limb from list to cycle
        limbs.Remove(limb);
    }
Ejemplo n.º 35
0
        public override void Update(float deltaTime, Camera cam)
        {
            if (!item.body.Enabled)
            {
                return;
            }
            if (picker == null || picker.Removed || !picker.HasSelectedItem(item))
            {
                IsActive = false;
                return;
            }

            if (picker.IsKeyDown(InputType.Aim) && picker.IsKeyHit(InputType.Use))
            {
                throwing = true;
            }

            if (!picker.IsKeyDown(InputType.Aim) && !throwing)
            {
                throwPos = 0.0f;
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);

            if (item.body.Dir != picker.AnimController.Dir)
            {
                Flip();
            }

            AnimController ac = picker.AnimController;

            item.Submarine = picker.Submarine;

            if (!throwing)
            {
                if (picker.IsKeyDown(InputType.Aim))
                {
                    throwPos = MathUtils.WrapAnglePi(System.Math.Min(throwPos + deltaTime * 5.0f, MathHelper.PiOver2));
                    ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, false, throwPos);
                }
                else
                {
                    throwPos = 0;
                    ac.HoldItem(deltaTime, item, handlePos, holdPos, Vector2.Zero, false, holdAngle);
                }
            }
            else
            {
                throwPos = MathUtils.WrapAnglePi(throwPos - deltaTime * 15.0f);
                ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, false, throwPos);

                if (throwPos < 0)
                {
                    Vector2 throwVector = Vector2.Normalize(picker.CursorWorldPosition - picker.WorldPosition);
                    //throw upwards if cursor is at the position of the character
                    if (!MathUtils.IsValid(throwVector))
                    {
                        throwVector = Vector2.UnitY;
                    }

#if SERVER
                    GameServer.Log(picker.LogName + " threw " + item.Name, ServerLog.MessageType.ItemInteraction);
#endif

                    item.Drop(picker, createNetworkEvent: GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer);
                    item.body.ApplyLinearImpulse(throwVector * throwForce * item.body.Mass * 3.0f);

                    ac.GetLimb(LimbType.Head).body.ApplyLinearImpulse(throwVector * 10.0f);
                    ac.GetLimb(LimbType.Torso).body.ApplyLinearImpulse(throwVector * 10.0f);

                    Limb rightHand = ac.GetLimb(LimbType.RightHand);
                    item.body.AngularVelocity = rightHand.body.AngularVelocity;
                    throwPos  = 0;
                    throwDone = true;
                    ApplyStatusEffects(ActionType.OnSecondaryUse, deltaTime, picker); //Stun grenades, flares, etc. all have their throw-related things handled in "onSecondaryUse"
                    throwing = false;
                }
            }
        }
Ejemplo n.º 36
0
        // Not sure if using the copy function is the best method
        /// <summary>
        /// Recursively generates all of the possible body part combinations for the two stock.
        /// This can create duplicates.
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <param name="possibleBodyParts"></param>
        /// <param name="limb"></param>
        /// <returns></returns>
        private List <Dictionary <Limb, Side> > GenerateBodyParts(Stock left, Stock right,
                                                                  Dictionary <Limb, Side> possibleBodyParts, Limb limb)
        {
            List <Dictionary <Limb, Side> > bodyPartsList = new List <Dictionary <Limb, Side> >();

            // End condition
            if (limb > Limb.Claws)
            {
                bodyPartsList.Add(possibleBodyParts);
                return(bodyPartsList);
            }

            // Build left side possible body parts
            if (left.BodyParts[limb])
            {
                possibleBodyParts[limb] = Side.Left;
            }
            else
            {
                possibleBodyParts[limb] = Side.Empty;
            }
            bodyPartsList.AddRange(GenerateBodyParts(left, right, CopyBodyParts(possibleBodyParts), limb + 1));

            // Build right side possible body parts
            if (right.BodyParts[limb])
            {
                possibleBodyParts[limb] = Side.Right;
            }
            else
            {
                possibleBodyParts[limb] = Side.Empty;
            }
            bodyPartsList.AddRange(GenerateBodyParts(left, right, CopyBodyParts(possibleBodyParts), limb + 1));

            return(bodyPartsList);
        }
Ejemplo n.º 37
0
        public override void Update(float deltaTime, Camera cam)
        {
            if (!item.body.Enabled)
            {
                return;
            }
            if (midAir)
            {
                if (item.body.LinearVelocity.LengthSquared() < 0.01f)
                {
                    CurrentThrower = null;
                    if (statusEffectLists?.ContainsKey(ActionType.OnImpact) ?? false)
                    {
                        foreach (var statusEffect in statusEffectLists[ActionType.OnImpact])
                        {
                            statusEffect.SetUser(null);
                        }
                    }
                    if (statusEffectLists?.ContainsKey(ActionType.OnBroken) ?? false)
                    {
                        foreach (var statusEffect in statusEffectLists[ActionType.OnBroken])
                        {
                            statusEffect.SetUser(null);
                        }
                    }
                    item.body.CollidesWith = Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionPlatform;
                    midAir = false;
                }
                return;
            }

            if (picker == null || picker.Removed || !picker.HasSelectedItem(item))
            {
                IsActive = false;
                return;
            }

            if (picker.IsKeyDown(InputType.Aim) && picker.IsKeyHit(InputType.Shoot))
            {
                throwing = true;
            }
            if (!picker.IsKeyDown(InputType.Aim) && !throwing)
            {
                throwPos = 0.0f;
            }
            bool aim = picker.IsKeyDown(InputType.Aim) && picker.CanAim;

            if (picker.IsDead || !picker.AllowInput)
            {
                throwing = false;
                aim      = false;
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);

            if (item.body.Dir != picker.AnimController.Dir)
            {
                item.FlipX(relativeToSub: false);
            }

            AnimController ac = picker.AnimController;

            item.Submarine = picker.Submarine;

            if (!throwing)
            {
                if (aim)
                {
                    throwPos = MathUtils.WrapAnglePi(System.Math.Min(throwPos + deltaTime * 5.0f, MathHelper.PiOver2));
                    ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, false, throwPos);
                }
                else
                {
                    throwPos = 0;
                    ac.HoldItem(deltaTime, item, handlePos, holdPos, Vector2.Zero, false, holdAngle);
                }
            }
            else
            {
                throwPos = MathUtils.WrapAnglePi(throwPos - deltaTime * 15.0f);
                ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, false, throwPos);

                if (throwPos < 0)
                {
                    Vector2 throwVector = Vector2.Normalize(picker.CursorWorldPosition - picker.WorldPosition);
                    //throw upwards if cursor is at the position of the character
                    if (!MathUtils.IsValid(throwVector))
                    {
                        throwVector = Vector2.UnitY;
                    }

#if SERVER
                    GameServer.Log(GameServer.CharacterLogName(picker) + " threw " + item.Name, ServerLog.MessageType.ItemInteraction);
#endif
                    CurrentThrower = picker;
                    if (statusEffectLists?.ContainsKey(ActionType.OnImpact) ?? false)
                    {
                        foreach (var statusEffect in statusEffectLists[ActionType.OnImpact])
                        {
                            statusEffect.SetUser(CurrentThrower);
                        }
                    }
                    if (statusEffectLists?.ContainsKey(ActionType.OnBroken) ?? false)
                    {
                        foreach (var statusEffect in statusEffectLists[ActionType.OnBroken])
                        {
                            statusEffect.SetUser(CurrentThrower);
                        }
                    }

                    item.Drop(CurrentThrower, createNetworkEvent: GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer);
                    item.body.ApplyLinearImpulse(throwVector * ThrowForce * item.body.Mass * 3.0f, maxVelocity: NetConfig.MaxPhysicsBodyVelocity);

                    //disable platform collisions until the item comes back to rest again
                    item.body.CollidesWith = Physics.CollisionWall | Physics.CollisionLevel;
                    midAir = true;

                    ac.GetLimb(LimbType.Head).body.ApplyLinearImpulse(throwVector * 10.0f, maxVelocity: NetConfig.MaxPhysicsBodyVelocity);
                    ac.GetLimb(LimbType.Torso).body.ApplyLinearImpulse(throwVector * 10.0f, maxVelocity: NetConfig.MaxPhysicsBodyVelocity);

                    Limb rightHand = ac.GetLimb(LimbType.RightHand);
                    item.body.AngularVelocity = rightHand.body.AngularVelocity;
                    throwPos  = 0;
                    throwDone = true;

                    if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer)
                    {
                        GameMain.NetworkMember.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.ApplyStatusEffect, ActionType.OnSecondaryUse, this, CurrentThrower.ID });
                    }
                    if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
                    {
                        //Stun grenades, flares, etc. all have their throw-related things handled in "onSecondaryUse"
                        ApplyStatusEffects(ActionType.OnSecondaryUse, deltaTime, CurrentThrower, user: CurrentThrower);
                    }
                    throwing = false;
                }
            }
        }
Ejemplo n.º 38
0
 override public void SwitchToFK(Limb sender)
 {
     distJoint.enabled   = true;
     targetJoint.enabled = false;
     parent.SwitchToFK(this);
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Set this bodypart to ignore collisions with another bodypart.
 /// This is useful if you want players on the same team to not collide with each other despite
 /// being in the same layer
 /// </summary>
 /// <param name="bodypart"></param>
 public void SetToIgnoreCollision(Limb bodypart)
 {
     Physics2D.IgnoreCollision(collider, bodypart.collider);
 }
 public void Init(Limb constraint)
 {
     this.constraint     = constraint;
     constraintName.text = constraint.ToString();
     removeBtn.onClick.AddListener(() => RemoveConstraint());
 }
Ejemplo n.º 41
0
        public override void Update(float deltaTime, Camera cam)
        {
            this.cam = cam;

            if (user == null ||
                user.Removed ||
                user.SelectedConstruction != item ||
                !user.CanInteractWith(item))
            {
                if (user != null)
                {
                    CancelUsing(user);
                    user = null;
                }
                IsActive = false;
                return;
            }

            user.AnimController.Anim = AnimController.Animation.UsingConstruction;

            if (userPos != Vector2.Zero)
            {
                Vector2 diff = (item.WorldPosition + userPos) - user.WorldPosition;

                if (user.AnimController.InWater)
                {
                    if (diff.Length() > 30.0f)
                    {
                        user.AnimController.TargetMovement = Vector2.Clamp(diff * 0.01f, -Vector2.One, Vector2.One);
                        user.AnimController.TargetDir      = diff.X > 0.0f ? Direction.Right : Direction.Left;
                    }
                    else
                    {
                        user.AnimController.TargetMovement = Vector2.Zero;
                    }
                }
                else
                {
                    diff.Y = 0.0f;
                    if (diff != Vector2.Zero && diff.LengthSquared() > 10.0f * 10.0f)
                    {
                        user.AnimController.TargetMovement = Vector2.Normalize(diff);
                        user.AnimController.TargetDir      = diff.X > 0.0f ? Direction.Right : Direction.Left;
                        return;
                    }
                    user.AnimController.TargetMovement = Vector2.Zero;
                }
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, user);

            if (limbPositions.Count == 0)
            {
                return;
            }

            user.AnimController.Anim = AnimController.Animation.UsingConstruction;

            user.AnimController.ResetPullJoints();

            if (dir != 0)
            {
                user.AnimController.TargetDir = dir;
            }

            foreach (LimbPos lb in limbPositions)
            {
                Limb limb = user.AnimController.GetLimb(lb.limbType);
                if (limb == null || !limb.body.Enabled)
                {
                    continue;
                }

                limb.Disabled = true;

                Vector2 worldPosition = new Vector2(item.WorldRect.X, item.WorldRect.Y) + lb.position * item.Scale;
                Vector2 diff          = worldPosition - limb.WorldPosition;

                limb.PullJointEnabled      = true;
                limb.PullJointWorldAnchorB = limb.SimPosition + ConvertUnits.ToSimUnits(diff);
            }
        }
Ejemplo n.º 42
0
        private bool OnCollision(Fixture f1, Fixture f2, Contact contact)
        {
            if (User == null || User.Removed)
            {
                RestoreCollision();
                hitting = false;
                User    = null;
            }

            //ignore collision if there's a wall between the user and the weapon to prevent hitting through walls
            if (Submarine.PickBody(User.AnimController.AimSourceSimPos,
                                   item.SimPosition,
                                   collisionCategory: Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionItemBlocking,
                                   allowInsideFixture: true) != null)
            {
                return(false);
            }

            Character targetCharacter = null;
            Limb      targetLimb      = null;
            Structure targetStructure = null;
            Item      targetItem      = null;

            attack?.SetUser(User);

            if (f2.Body.UserData is Limb)
            {
                targetLimb = (Limb)f2.Body.UserData;
                if (targetLimb.IsSevered || targetLimb.character == null)
                {
                    return(false);
                }
                targetCharacter = targetLimb.character;
                if (targetCharacter == picker)
                {
                    return(false);
                }
                if (AllowHitMultiple)
                {
                    if (hitTargets.Contains(targetCharacter))
                    {
                        return(false);
                    }
                }
                else
                {
                    if (hitTargets.Any(t => t is Character))
                    {
                        return(false);
                    }
                }
                hitTargets.Add(targetCharacter);
            }
            else if (f2.Body.UserData is Character)
            {
                targetCharacter = (Character)f2.Body.UserData;
                if (targetCharacter == picker)
                {
                    return(false);
                }
                targetLimb = targetCharacter.AnimController.GetLimb(LimbType.Torso); //Otherwise armor can be bypassed in strange ways
                if (AllowHitMultiple)
                {
                    if (hitTargets.Contains(targetCharacter))
                    {
                        return(false);
                    }
                }
                else
                {
                    if (hitTargets.Any(t => t is Character))
                    {
                        return(false);
                    }
                }
                hitTargets.Add(targetCharacter);
            }
            else if (f2.Body.UserData is Structure)
            {
                targetStructure = (Structure)f2.Body.UserData;
                if (AllowHitMultiple)
                {
                    if (hitTargets.Contains(targetStructure))
                    {
                        return(true);
                    }
                }
                else
                {
                    if (hitTargets.Any(t => t is Structure))
                    {
                        return(true);
                    }
                }
                hitTargets.Add(targetStructure);
            }
            else if (f2.Body.UserData is Item)
            {
                targetItem = (Item)f2.Body.UserData;
                if (AllowHitMultiple)
                {
                    if (hitTargets.Contains(targetItem))
                    {
                        return(true);
                    }
                }
                else
                {
                    if (hitTargets.Any(t => t is Item))
                    {
                        return(true);
                    }
                }
                hitTargets.Add(targetItem);
            }
            else
            {
                return(false);
            }

            if (attack != null)
            {
                if (targetLimb != null)
                {
                    targetLimb.character.LastDamageSource = item;
                    attack.DoDamageToLimb(User, targetLimb, item.WorldPosition, 1.0f);
                }
                else if (targetCharacter != null)
                {
                    targetCharacter.LastDamageSource = item;
                    attack.DoDamage(User, targetCharacter, item.WorldPosition, 1.0f);
                }
                else if (targetStructure != null)
                {
                    attack.DoDamage(User, targetStructure, item.WorldPosition, 1.0f);
                }
                else if (targetItem != null && targetItem.Prefab.DamagedByMeleeWeapons)
                {
                    attack.DoDamage(User, targetItem, item.WorldPosition, 1.0f);
                }
                else
                {
                    return(false);
                }
            }

            if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
            {
                return(true);
            }

#if SERVER
            if (GameMain.Server != null && targetCharacter != null) //TODO: Log structure hits
            {
                GameMain.Server.CreateEntityEvent(item, new object[]
                {
                    Networking.NetEntityEvent.Type.ApplyStatusEffect,
                    ActionType.OnUse,
                    null, //itemcomponent
                    targetCharacter.ID, targetLimb
                });

                string logStr = picker?.LogName + " used " + item.Name;
                if (item.ContainedItems != null && item.ContainedItems.Any())
                {
                    logStr += " (" + string.Join(", ", item.ContainedItems.Select(i => i?.Name)) + ")";
                }
                logStr += " on " + targetCharacter.LogName + ".";
                Networking.GameServer.Log(logStr, Networking.ServerLog.MessageType.Attack);
            }
#endif

            if (targetCharacter != null) //TODO: Allow OnUse to happen on structures too maybe??
            {
                ApplyStatusEffects(ActionType.OnUse, 1.0f, targetCharacter, targetLimb, user: User);
            }

            if (DeleteOnUse)
            {
                Entity.Spawner.AddToRemoveQueue(item);
            }

            return(true);
        }
 public override void Update(CharacterHealth characterHealth, Limb targetLimb, float deltaTime)
 {
     base.Update(characterHealth, targetLimb, deltaTime);
     UpdateProjSpecific(characterHealth, targetLimb, deltaTime);
 }
    /// <summary>
    /// Returns a limb with the specified damage applied to it, including layer penetration/spillover.
    /// </summary>
    /// <param name="damage"></param>
    /// <param name="limb"></param>
    /// <returns></returns>
    public Limb DamageLimb(BodyPartDamage damage, Limb limb)
    {
        // Pick a hypothetical full-penetration path, rolling weighted draws based on volume at each layer
        BodyPart[] targets = (from layer in limb.Layers
                              select(BodyPart) Util.WeightedRandomDraw(choices: layer,
                                                                       weights: (from p in layer select p.Volume).ToArray())).ToArray();

        // Record targets' current integrities as an initial-state reference
        float[] initial_integrities = (from tgt in targets select tgt.Integrity).ToArray();

        // Create a tally of remaining damage to be distributed
        BodyPartDamage dmg_left = damage;

        // Iterate through targets, going outside in and breaking early if we run out of damage to distribute.
        for (int i = targets.Length - 1; i >= 0; i--)
        {
            // Identify the index of this part in its own layer array
            int part_index = Array.IndexOf(limb.Layers[i], targets[i]);

            // Apply impact damage, in whole or in part
            if (dmg_left.Impact / initial_integrities[i] > ImpactSpilloverPoint)
            {
                // With spillover
                float impact_amt = dmg_left.Impact * ImpactSpilloverPoint;
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(impact: impact_amt),
                                                        part: targets[i]);
                dmg_left.Impact -= impact_amt;
            }
            else
            {
                // Without spillover
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(impact: dmg_left.Impact),
                                                        part: limb.Layers[i][part_index]);

                dmg_left.Impact = 0f;
            }

            // Apply shear damage, in whole or part
            if (dmg_left.Shear / initial_integrities[i] > ShearSpilloverPoint)
            {
                // With spillover
                float shear_amt = dmg_left.Shear * ShearSpilloverPoint;
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(shear: shear_amt),
                                                        part: limb.Layers[i][part_index]);

                dmg_left.Shear -= shear_amt;
            }
            else
            {
                // Without spillover
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(shear: dmg_left.Shear),
                                                        part: limb.Layers[i][part_index]);

                dmg_left.Shear = 0f;
            }

            // Apply corrosive damage, in whole or part
            if (dmg_left.Corrosive / initial_integrities[i] > CorrosiveSpilloverPoint)
            {
                // With spillover
                float corrosive_amt = dmg_left.Corrosive * CorrosiveSpilloverPoint;
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(corrosive: corrosive_amt),
                                                        part: limb.Layers[i][part_index]);

                dmg_left.Corrosive -= corrosive_amt;
            }
            else
            {
                // Without spillover
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(corrosive: dmg_left.Corrosive),
                                                        part: limb.Layers[i][part_index]);

                dmg_left.Corrosive = 0f;
            }

            // Apply energy damage, in whole or part
            if (dmg_left.Energy / initial_integrities[i] > EnergySpilloverPoint)
            {
                // With spillover
                float energy_amt = dmg_left.Energy * EnergySpilloverPoint;
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(energy: energy_amt),
                                                        part: limb.Layers[i][part_index]);

                dmg_left.Energy -= energy_amt;
            }
            else
            {
                // Without spillover
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(energy: dmg_left.Energy),
                                                        part: limb.Layers[i][part_index]);

                dmg_left.Energy = 0f;
            }

            // Lastly, if no further damage is left to spill over, break the loop.
            // Otherwise, we'll carry that damage forward one layer deeper.
            if (dmg_left.Impact + dmg_left.Shear + dmg_left.Corrosive + dmg_left.Energy == 0)
            {
                break;
            }
        }

        // If any damage remains after all penetration has been accounted for,
        // then divide it evenly among parts which were damaged by this attack.
        if (dmg_left.Impact + dmg_left.Shear + dmg_left.Corrosive + dmg_left.Energy != 0)
        {
            for (int i = targets.Length - 1; i >= 0; i--)
            {
                int part_index = Array.IndexOf(limb.Layers[i], targets[i]);
                limb.Layers[i][part_index] = DamagePart(damage: new BodyPartDamage(impact: dmg_left.Impact / targets.Length,
                                                                                   shear: dmg_left.Shear / targets.Length,
                                                                                   corrosive: dmg_left.Corrosive / targets.Length,
                                                                                   energy: dmg_left.Energy / targets.Length),
                                                        part: limb.Layers[i][part_index]);
            }
        }

        // Finally, return the transmuted Limb.
        return(limb);
    }
 public limbCheckboxWrapper(Frame_SelectTreatment_Gnome gnome, Button btn, Limb limb)
 {
     Gnome        = gnome;
     Button       = btn;
     Limb         = limb;
     initial_text = btn.Text;
     Update();
     btn.Click += new EventHandler((sender, args) =>
     {
         Gnome.OnTreatmentPlanChanged(Gnome.treatRecord.Get_ToggleLimb(Limb));
         Update();
         Gnome.updateLimbCheckbox();
     });
 }
Ejemplo n.º 46
0
				public bool _PrepareLimbRotation( Limb limb, int i, int origIndex, ref Vector3 beginPos )
				{
					Assert( i < 2 );
					this.origTheta[i] = 0.0f;
					this.origAxis[i] = new Vector3( 0.0f, 0.0f, 1.0f );

					if( !limb.targetBeginPosEnabled[i] ) {
						return false;
					}

					// Memo: limb index = orig index.

					var targetBeginPos = limb.targetBeginPos;

					Vector3 origPos = (origIndex == -1) ? this.centerLegPos : this.spinePos[origIndex];

					return _ComputeThetaAxis(
						ref origPos,
						ref beginPos,
						ref targetBeginPos[i],
						out this.origTheta[i],
						out this.origAxis[i] );
				}
Ejemplo n.º 47
0
        public override void Update(float deltaTime, Camera cam)
        {
            if (item.body == null || !item.body.Enabled)
            {
                return;
            }
            if (picker == null || !picker.HasEquippedItem(item))
            {
                if (Pusher != null)
                {
                    Pusher.Enabled = false;
                }
                IsActive = false;
                return;
            }

            Vector2 swing = Vector2.Zero;

            if (swingAmount != Vector2.Zero && !picker.IsUnconscious && picker.Stun <= 0.0f)
            {
                swingState += deltaTime;
                swingState %= 1.0f;
                if (SwingWhenHolding ||
                    (SwingWhenAiming && picker.IsKeyDown(InputType.Aim)) ||
                    (SwingWhenUsing && picker.IsKeyDown(InputType.Aim) && picker.IsKeyDown(InputType.Shoot)))
                {
                    swing = swingAmount * new Vector2(
                        PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f, swingState * SwingSpeed * 0.1f) - 0.5f,
                        PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f + 0.5f, swingState * SwingSpeed * 0.1f + 0.5f) - 0.5f);
                }
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);

            if (item.body.Dir != picker.AnimController.Dir)
            {
                item.FlipX(relativeToSub: false);
            }

            item.Submarine = picker.Submarine;

            if (picker.HasSelectedItem(item))
            {
                scaledHandlePos[0] = handlePos[0] * item.Scale;
                scaledHandlePos[1] = handlePos[1] * item.Scale;
                bool aim = picker.IsKeyDown(InputType.Aim) && aimPos != Vector2.Zero && picker.CanAim;
                picker.AnimController.HoldItem(deltaTime, item, scaledHandlePos, holdPos + swing, aimPos + swing, aim, holdAngle);
            }
            else
            {
                Limb equipLimb = null;
                if (picker.Inventory.IsInLimbSlot(item, InvSlotType.Headset) || picker.Inventory.IsInLimbSlot(item, InvSlotType.Head))
                {
                    equipLimb = picker.AnimController.GetLimb(LimbType.Head);
                }
                else if (picker.Inventory.IsInLimbSlot(item, InvSlotType.InnerClothes) ||
                         picker.Inventory.IsInLimbSlot(item, InvSlotType.OuterClothes))
                {
                    equipLimb = picker.AnimController.GetLimb(LimbType.Torso);
                }

                if (equipLimb != null)
                {
                    float itemAngle = (equipLimb.Rotation + holdAngle * picker.AnimController.Dir);

                    Matrix  itemTransfrom        = Matrix.CreateRotationZ(equipLimb.Rotation);
                    Vector2 transformedHandlePos = Vector2.Transform(handlePos[0] * item.Scale, itemTransfrom);

                    item.body.ResetDynamics();
                    item.SetTransform(equipLimb.SimPosition - transformedHandlePos, itemAngle);
                }
            }
        }
Ejemplo n.º 48
0
				bool _SolveLimbRotation( Limb limb, int origIndex, out Quaternion origRotation )
				{
					origRotation = Quaternion.identity;

					int pullIndex = -1;
					int pullLength = 0;
					for( int i = 0; i < 2; ++i ) {
						if( limb.targetBeginPosEnabled[i] ) {
							pullIndex = i;
							++pullLength;
						}
					}

					if( pullLength == 0 ) {
						return false; // Failsafe.
					}

					float lerpRate = (limb == arms) ? _solverCaches.limbArmRate : _solverCaches.limbLegRate;

					if( pullLength == 1 ) {
						int i0 = pullIndex;
						if( this.origTheta[i0] == 0.0f ) {
							return false;
						}

						if( i0 == 0 ) {
							lerpRate = 1.0f - lerpRate;
						}

						origRotation = _GetRotation( ref this.origAxis[i0], this.origTheta[i0], this.origFeedbackRate[i0] * lerpRate );
						return true;
					}

					// Fix for rotate 180 degrees or more.( half rotation in GetRotation & double rotation in origRotation * origRotation. )
					Quaternion origRotation0 = _GetRotation( ref this.origAxis[0], this.origTheta[0], this.origFeedbackRate[0] * 0.5f );
					Quaternion origRotation1 = _GetRotation( ref this.origAxis[1], this.origTheta[1], this.origFeedbackRate[1] * 0.5f );
					origRotation = Quaternion.Lerp( origRotation0, origRotation1, lerpRate );
					origRotation = origRotation * origRotation; // Optimized: Not normalize.
					return true;
				}
Ejemplo n.º 49
0
 public Body(String name, Limb limb)
 {
     this.name = name;
     this.limb = limb;
 }
Ejemplo n.º 50
0
				bool _PrepareLimbTranslate( Limb limb, int i, ref Vector3 beginPos )
				{
					this.origTranslate[i] = Vector3.zero;
					if( limb.targetBeginPosEnabled[i] ) {
						this.origTranslate[i] = (limb.targetBeginPos[i] - beginPos);
						return true;
					}

					return false;
				}
Ejemplo n.º 51
0
        private bool OnProjectileCollision(Fixture target, Vector2 collisionNormal)
        {
            if (IgnoredBodies.Contains(target.Body))
            {
                return(false);
            }

            if (target.CollisionCategories == Physics.CollisionCharacter && !(target.Body.UserData is Limb))
            {
                return(false);
            }

            AttackResult attackResult = new AttackResult();
            Character    character    = null;

            if (attack != null)
            {
                var submarine = target.Body.UserData as Submarine;
                if (submarine != null)
                {
                    item.Move(-submarine.Position);
                    item.Submarine      = submarine;
                    item.body.Submarine = submarine;
                    return(true);
                }

                Limb      limb = target.Body.UserData as Limb;
                Structure structure;
                if (limb != null)
                {
                    attackResult = attack.DoDamageToLimb(User, limb, item.WorldPosition, 1.0f);
                    if (limb.character != null)
                    {
                        character = limb.character;
                    }
                }
                else if ((structure = (target.Body.UserData as Structure)) != null)
                {
                    attackResult = attack.DoDamage(User, structure, item.WorldPosition, 1.0f);
                }
            }

            ApplyStatusEffects(ActionType.OnUse, 1.0f, character);
            ApplyStatusEffects(ActionType.OnImpact, 1.0f, character);

            item.body.FarseerBody.OnCollision -= OnProjectileCollision;

            item.body.CollisionCategories = Physics.CollisionItem;
            item.body.CollidesWith        = Physics.CollisionWall | Physics.CollisionLevel;

            IgnoredBodies.Clear();

            target.Body.ApplyLinearImpulse(item.body.LinearVelocity * item.body.Mass);

            if (attackResult.AppliedDamageModifiers != null &&
                attackResult.AppliedDamageModifiers.Any(dm => dm.DeflectProjectiles))
            {
                item.body.LinearVelocity *= 0.1f;
            }
            else if (Vector2.Dot(item.body.LinearVelocity, collisionNormal) < 0.0f &&
                     (DoesStick ||
                      (StickToCharacters && target.Body.UserData is Limb) ||
                      (StickToStructures && target.Body.UserData is Structure) ||
                      (StickToItems && target.Body.UserData is Item)))
            {
                Vector2 dir = new Vector2(
                    (float)Math.Cos(item.body.Rotation),
                    (float)Math.Sin(item.body.Rotation));

                StickToTarget(target.Body, dir);
                item.body.LinearVelocity *= 0.5f;

                return(Hitscan);
            }
            else
            {
                item.body.LinearVelocity *= 0.5f;
            }

            var containedItems = item.ContainedItems;

            if (containedItems != null)
            {
                foreach (Item contained in containedItems)
                {
                    if (contained.body != null)
                    {
                        contained.SetTransform(item.SimPosition, contained.body.Rotation);
                    }
                    //contained.Condition = 0.0f; //Let the freaking .xml handle it jeez
                }
            }

            if (RemoveOnHit)
            {
                Item.Spawner.AddToRemoveQueue(item);
            }

            return(true);
        }
Ejemplo n.º 52
0
    public static AnimationBehaviour GetBehaviour(Movement m, Limb l)
    {
        int mov_search = (int)m / MAGIC_NUMBER;
        AnimationBehaviour encontrado = null;
        Animator a = GameObject.FindObjectOfType<AnimatorScript>().anim;
        AnimationBehaviour[] behaviours = a.GetBehaviours<AnimationBehaviour>();

        foreach (AnimationBehaviour lb in behaviours)
        {
            int lb_mov = (int)lb.movement / MAGIC_NUMBER;
            if (lb_mov == mov_search)
            {
                if (lb.animator == null)
                    lb.animator = a;

                if (lb.IsCentralNode && lb.limb == l)
                {
                    // Si se encontró un nodo central que calce con el 'Movement' entonces se retorna.
                    encontrado = lb;
                    break;
                }
                else if (!lb.HasCentralNode && lb.movement == m && l == lb.limb)
                    encontrado = lb;
            }
        }
        // Si no es un movimiento con nodo central, entonces se retorna. Se asume sin problemas que es el único encontrado.
        return encontrado;
    }