Beispiel #1
0
 private static Vector3 RoundVector(Vector3 vec, float rounding)
 {
     return(new Vector3(Mathf.Ceil(vec.x / rounding) * rounding, Mathf.Ceil(vec.y / rounding) * rounding, Mathf.Ceil(vec.z / rounding) * rounding));
 }
Beispiel #2
0
    IEnumerator UpdateScoreIfNeeded()
    {
        int counter = 1;

        yield return(StartCoroutine(GetLapScore.GetTimes()));

        yield return(new WaitForSeconds(1));

        foreach (string s in GetLapScore.times.Split('~'))
        {
            if (s == "")
            {
                break;
            }
            Debug.LogError(s);
            string[] sA = s.Split('|');
            if (int.Parse(sA[1]) == int.Parse(SceneManager.GetActiveScene().name.Remove(0, 5)) - 1)
            {
                Debug.LogWarning(sA[5]);
                if (timer < int.Parse(sA[5]))
                {
                    StartCoroutine(UpdateLapScore.UpdateScores((int.Parse(SceneManager.GetActiveScene().name.Remove(0, 5)) - 1).ToString(), Mathf.Ceil(timer).ToString(), counter));
                    break;
                }
            }
            counter++;
        }
    }
Beispiel #3
0
        public override bool Spawn(bool placing = false)
        {
            if (!(data.Has("sourceid", "destid", "sourcechildid", "destchildid")))
            {
                return(false);
            }

            uint sourceid = uint.Parse(data.Get("sourceid"));
            uint destid   = uint.Parse(data.Get("destid"));

            sourcechildid = uint.Parse(data.Get("sourcechildid"));
            destchildid   = uint.Parse(data.Get("destchildid"));

            sourcecont = GetChildContainer(BaseNetworkable.serverEntities.Find(sourceid), sourcechildid);
            destcont   = GetChildContainer(BaseNetworkable.serverEntities.Find(destid), destchildid);

            if (sourcecont == null || destcont == null || sourcecont == destcont)
            {
                return(false);
            }

            sourceContainerIconUrl = Icons.GetContainerIconURL(sourcecont, 100);
            destContainerIconUrl   = Icons.GetContainerIconURL(destcont, 100);

            isWaterPipe     = sourcecont is LiquidContainer;
            destisstartable = IsStartable(destcont);
            flowrate        = flowrates[int.Parse(data.Get("grade", "0"))];
            mode            = (Mode)int.Parse(data.Get("mode", "0"));

            startPosition = sourcecont.CenterPoint() + ContainerOffset(sourcecont);
            endPosition   = destcont.CenterPoint() + ContainerOffset(destcont);

            distance = Vector3.Distance(startPosition, endPosition);
            Quaternion rotation = Quaternion.LookRotation(endPosition - startPosition) * Quaternion.Euler(0, 0, 0);

            //isStartable();

            // spawn pillars

            int   segments = (int)Mathf.Ceil(distance / pipesegdist);
            float segspace = (distance - pipesegdist) / (segments - 1);

            startPosition = startPosition + ((rotation * Vector3.forward) * pipesegdist * 0.5f) + ((rotation * Vector3.down) * 0.7f);
            for (int i = 0; i < segments; i++)
            {
                // create pillar

                BaseEntity ent;

                if (i == 0)
                {
                    // the position thing centers the pipe if there is only one segment
                    ent = GameManager.server.CreateEntity("assets/prefabs/building core/wall.low/wall.low.prefab", (segments == 1) ? (startPosition + ((rotation * Vector3.up) * ((distance - pipesegdist) * 0.5f))) : startPosition, rotation);
                    SetMainParent((BaseCombatEntity)ent);
                }
                else
                {
                    ent = GameManager.server.CreateEntity("assets/prefabs/building core/wall.low/wall.low.prefab", Vector3.forward * (segspace * i) + ((i % 2 == 0) ? Vector3.zero : pipefightoffset));
                    //ent = GameManager.server.CreateEntity("assets/prefabs/building core/pillar/pillar.prefab", startPosition);
                }

                ent.enableSaving = false;

                BuildingBlock block = ent.GetComponent <BuildingBlock>();

                if (block != null)
                {
                    block.grounded     = true;
                    block.grade        = (BuildingGrade.Enum) int.Parse(data.Get("grade", "0"));
                    block.enableSaving = false;
                    block.Spawn();
                    block.SetHealthToMax();
                }
                else
                {
                    return(false);
                }


                //((DecayEntity) ent).GetNearbyBuildingBlock();

                if (i != 0)
                {
                    if (placing)                       // placing animation
                    {
                        ent.gameObject.AddComponent <Child>()?.RunDelayed(i * 0.25f, () => {
                            AddChildEntity((BaseCombatEntity)ent);
                            Effect.server.Run("assets/bundled/prefabs/fx/build/promote_wood.prefab", ent.transform.position + (ent.transform.up * (segspace * 0.5f)), Vector3.up);
                        });
                    }
                    else
                    {
                        AddChildEntity((BaseCombatEntity)ent);
                    }
                }

                // xmas lights

                //BaseEntity lights = GameManager.server.CreateEntity("assets/prefabs/misc/xmas/christmas_lights/xmas.lightstring.deployed.prefab", (Vector3.up * pipesegdist * 0.5f) + (Vector3.forward * 0.13f) + (Vector3.up * (segspace * i) + ((i % 2 == 0) ? Vector3.zero : pipefightoffset)), Quaternion.Euler(0, -60, 90));
                //lights.enableSaving = false;
                //lights.Spawn();
                //lights.SetParent(mainparent);
                //jPipeSegChildLights.Attach(lights, this);
            }

            if (placing)
            {
                SetHealth(GetEntities()[0].MaxHealth());
            }
            else
            {
                SetHealth(data.health);
            }

            return(true);
        }
Beispiel #4
0
    void DrawTestEnv(string env)
    {
        switch (env)
        {
        case "1":
            for (int i = 0; i < WIDTH * HEIGHT; i++)
            {
                int x = i % WIDTH;
                int y = i / HEIGHT;
                if (y == 30 && x > 10 && x < 20)
                {
                    AddParticle(PARTICLE_TYPE.WALL, x, y);
                }
                if ((x == 10 || x == 20) && y > 30 && y < 40)
                {
                    AddParticle(PARTICLE_TYPE.WALL, x, y);
                }
                if (y == 30 && x > 60 && x < 70)
                {
                    AddParticle(PARTICLE_TYPE.WALL, x, y);
                }

                if ((x == 60 || x == 70) && y > 30 && y < 40)
                {
                    AddParticle(PARTICLE_TYPE.WALL, x, y);
                }
            }
            RemoveParticle(12, 30);

            // Diag top left -> bot right
            for (int i = 0; i < 10; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 21 + i, 40 - i);
            }
            // Diag top right -> bot left
            for (int i = 0; i < 10; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 42 - i, 40 - i);
            }

            for (int i = 0; i < 10; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 22 + i, 16 + i);
            }
            for (int i = 0; i < 10; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 41 - i, 16 + i);
            }
            for (int i = 0; i < 9; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 2 + i, 50 - i);
            }

            AddParticle(PARTICLE_TYPE.WALL, 0, 50);
            AddParticle(PARTICLE_TYPE.WALL, 1, 51);

            // Diag top left -> bot right
            for (int i = 0; i < 10; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 55 + (int)Mathf.Ceil(i * .5f), 70 - i);
            }

            break;

        case "2":
            for (int i = 0; i < 10; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 21 + i, 40);
            }
            // Diag top left -> bot right
            for (int i = 0; i < 10; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 45 + i, 40 - i);
            }
            // Diag top right -> bot left
            for (int i = 0; i < 10; i++)
            {
                AddParticle(PARTICLE_TYPE.WALL, 42 - i, 40 - i);
            }
            break;

        case "3":
            AddParticle(PARTICLE_TYPE.WALL, 0, 0);
            AddParticle(PARTICLE_TYPE.WALL, WIDTH - 1, 0);
            AddParticle(PARTICLE_TYPE.WALL, WIDTH - 1, HEIGHT - 1);
            AddParticle(PARTICLE_TYPE.WALL, 0, HEIGHT - 1);
            break;
        }
    }
Beispiel #5
0
    void Update()
    {
        if (emit && emitTime != 0)
        {
            emitTime -= Time.deltaTime;
            if (emitTime == 0)
            {
                emitTime = -1;
            }
            if (emitTime < 0)
            {
                emit = false;
            }
        }

        if (!emit && points.Count == 0 && autoDestruct)
        {
            Destroy(o);
            Destroy(gameObject);
        }

        // early out if there is no camera
        if (!Camera.main)
        {
            return;
        }

        bool re = false;

        // if we have moved enough, create a new vertex and make sure we rebuild the mesh
        float theDistance = (lastPosition - transform.position).magnitude;

        if (emit)
        {
            if (theDistance > minVertexDistance)
            {
                bool make = false;
                if (points.Count < 3)
                {
                    make = true;
                }
                else
                {
                    Vector3 l1 = ((Point)points[points.Count - 2]).position - ((Point)points[points.Count - 3]).position;
                    Vector3 l2 = ((Point)points[points.Count - 1]).position - ((Point)points[points.Count - 2]).position;
                    if (Vector3.Angle(l1, l2) > maxAngle || theDistance > maxVertexDistance)
                    {
                        make = true;
                    }
                }

                if (make)
                {
                    Point p = new Point();
                    p.position    = transform.position;
                    p.timeCreated = Time.time;
                    points.Add(p);
                    lastPosition = transform.position;
                }
                else
                {
                    ((Point)points[points.Count - 1]).position    = transform.position;
                    ((Point)points[points.Count - 1]).timeCreated = Time.time;
                }
            }
            else if (points.Count > 0)
            {
                ((Point)points[points.Count - 1]).position    = transform.position;
                ((Point)points[points.Count - 1]).timeCreated = Time.time;
            }
        }

        if (!emit && lastFrameEmit && points.Count > 0)
        {
            ((Point)points[points.Count - 1]).lineBreak = true;
        }
        lastFrameEmit = emit;

        // approximate if we should rebuild the mesh or not
        if (points.Count > 1)
        {
            Vector3 cur1 = Camera.main.WorldToScreenPoint(((Point)points[0]).position);
            lastCameraPosition1.z = 0;
            Vector3 cur2 = Camera.main.WorldToScreenPoint(((Point)points[points.Count - 1]).position);
            lastCameraPosition2.z = 0;

            float distance = (lastCameraPosition1 - cur1).magnitude;
            distance += (lastCameraPosition2 - cur2).magnitude;

            if (distance > movePixelsForRebuild || Time.time - lastRebuildTime > maxRebuildTime)
            {
                re = true;
                lastCameraPosition1 = cur1;
                lastCameraPosition2 = cur2;
            }
        }
        else
        {
            re = true;
        }


        if (re)
        {
            lastRebuildTime = Time.time;

            ArrayList remove = new ArrayList();
            int       i      = 0;
            foreach (Point p in points)
            {
                // cull old points first
                if (Time.time - p.timeCreated > lifeTime)
                {
                    remove.Add(p);
                }
                i++;
            }

            foreach (Point p in remove)
            {
                points.Remove(p);
            }
            remove.Clear();

            if (points.Count > 1)
            {
                Vector3[] newVertices  = new Vector3[points.Count * 2];
                Vector2[] newUV        = new Vector2[points.Count * 2];
                int[]     newTriangles = new int[(points.Count - 1) * 6];
                Color[]   newColors    = new Color[points.Count * 2];

                i = 0;
                float curDistance = 0.00f;

                foreach (Point p in points)
                {
                    float time = (Time.time - p.timeCreated) / lifeTime;

                    Color color = Color.Lerp(Color.white, Color.clear, time);
                    if (colors != null && colors.Length > 0)
                    {
                        float colorTime = time * (colors.Length - 1);
                        float min       = Mathf.Floor(colorTime);
                        float max       = Mathf.Clamp(Mathf.Ceil(colorTime), 1, colors.Length - 1);
                        float lerp      = Mathf.InverseLerp(min, max, colorTime);
                        if (min >= colors.Length)
                        {
                            min = colors.Length - 1;
                        }
                        if (min < 0)
                        {
                            min = 0;
                        }
                        if (max >= colors.Length)
                        {
                            max = colors.Length - 1;
                        }
                        if (max < 0)
                        {
                            max = 0;
                        }
                        color = Color.Lerp(colors[(int)min], colors[(int)max], lerp);
                    }

                    float size = 1f;
                    if (sizes != null && sizes.Length > 0)
                    {
                        float sizeTime = time * (sizes.Length - 1);
                        float min      = Mathf.Floor(sizeTime);
                        float max      = Mathf.Clamp(Mathf.Ceil(sizeTime), 1, sizes.Length - 1);
                        float lerp     = Mathf.InverseLerp(min, max, sizeTime);
                        if (min >= sizes.Length)
                        {
                            min = sizes.Length - 1;
                        }
                        if (min < 0)
                        {
                            min = 0;
                        }
                        if (max >= sizes.Length)
                        {
                            max = sizes.Length - 1;
                        }
                        if (max < 0)
                        {
                            max = 0;
                        }
                        size = Mathf.Lerp(sizes[(int)min], sizes[(int)max], lerp);
                    }

                    Vector3 lineDirection = Vector3.zero;
                    if (i == 0)
                    {
                        lineDirection = p.position - ((Point)points[i + 1]).position;
                    }
                    else
                    {
                        lineDirection = ((Point)points[i - 1]).position - p.position;
                    }

                    // Vector3 vectorToCamera = Camera.main.transform.position - p.position;
                    Vector3 perpendicular = this.transform.up;

                    newVertices[i * 2]       = p.position + (perpendicular * (size * 0.5f));
                    newVertices[(i * 2) + 1] = p.position + (-perpendicular * (size * 0.5f));

                    newColors[i * 2] = newColors[(i * 2) + 1] = color;

                    newUV[i * 2]       = new Vector2(curDistance * uvLengthScale, 0);
                    newUV[(i * 2) + 1] = new Vector2(curDistance * uvLengthScale, 1);

                    if (i > 0 && !((Point)points[i - 1]).lineBreak)
                    {
                        if (higherQualityUVs)
                        {
                            curDistance += (p.position - ((Point)points[i - 1]).position).magnitude;
                        }
                        else
                        {
                            curDistance += (p.position - ((Point)points[i - 1]).position).sqrMagnitude;
                        }

                        newTriangles[(i - 1) * 6]       = (i * 2) - 2;
                        newTriangles[((i - 1) * 6) + 1] = (i * 2) - 1;
                        newTriangles[((i - 1) * 6) + 2] = i * 2;

                        newTriangles[((i - 1) * 6) + 3] = (i * 2) + 1;
                        newTriangles[((i - 1) * 6) + 4] = i * 2;
                        newTriangles[((i - 1) * 6) + 5] = (i * 2) - 1;
                    }

                    i++;
                }

                Mesh mesh = (o.GetComponent(typeof(MeshFilter)) as MeshFilter).mesh;
                mesh.Clear();
                mesh.vertices  = newVertices;
                mesh.colors    = newColors;
                mesh.uv        = newUV;
                mesh.triangles = newTriangles;
            }
        }
    }
    private void CalculateWeaponVariables(LocalPlayerController player)
    {
        // Total weight to distribute at the start of generating weapons
        float totalWeight = currentBaseWeaponWeight * player.weaponWeightScalar;

        Debug.Log("Player #" + player.playerIndex + " - Variables Weight: " + totalWeight);

        // List of remaining values to give weights
        List <VariableWeight> remainingVariables = weaponVariableDict.Values.ToList();
        int increments = 0;

        // Loop until all variables are maxed out or until totalWeight is depleted
        while (remainingVariables.Count > 0 && totalWeight > 0)
        {
            // Get a random value to assign weights to
            VariableWeight currentVar = GetBiasedVariable(remainingVariables.ToArray());

            float weightForValue;

            // If the weight is too low to distribute with random, just assign the weight left
            if (totalWeight > 0.3f)
            {
                // Assign random weight
                weightForValue = UnityEngine.Random.Range(0, totalWeight / 2);
            }
            else
            {
                // Assign left over value
                weightForValue = totalWeight;
            }

            // If this is an integer value, round to top to prevent getting stuck
            if (currentVar.isIntegerValue)
            {
                weightForValue = Mathf.Ceil(weightForValue);
            }

            // Assign the new weight to the dictionary entry to link later to the weapon
            currentVar.currentValue += weightForValue;

            // When the value is higher than its max
            if (currentVar.currentValue > currentVar.maxedWeight)
            {
                // Subtract the difference so it can be spent on other variables
                float difference = currentVar.currentValue - currentVar.maxedWeight;
                weightForValue -= difference;
                // Clamp to max value
                currentVar.currentValue = currentVar.maxedWeight;
                // Remove the current selected value from the remaining values so it won't be selected again
                remainingVariables.Remove(currentVar);
            }

            // Adjust the total weight left to distribute
            totalWeight -= weightForValue;

            if (increments > 1000)
            {
                Debug.LogError("Something went terribly wrong, leading to far too many loops in CalculateWeaponVariables().");
                break;
            }
            increments++;
        }

        Debug.Log("Finished variable distribution after: " + increments + " increments");
    }
Beispiel #7
0
    float calculatePixelPerfectCameraSize(bool pixelPerfect, Resolution res, float assetsPixelsPerUnit, float maxCameraHalfWidth, float maxCameraHalfHeight
                                          , float targetHalfWidth, float targetHalfHeight, Dimension targetDimension)
    {
        float maxHorizontalFOV = 2f * maxCameraHalfWidth;
        float maxVerticalFOV   = 2f * maxCameraHalfHeight;
        float targetWidth      = 2f * targetHalfWidth;
        float targetHeight     = 2f * targetHalfHeight;
        float AR = (float)res.width / res.height;

        // How many screen pixels will an asset pixel render to?
        // or how many times will the asset dimensions be multiplied?
        float ratioTarget;

        if (targetDimension == Dimension.Width)
        {
            float assetsWidth = assetsPixelsPerUnit * targetWidth;
            ratioTarget = (float)res.width / assetsWidth;
        }
        else
        {
            float assetsHeight = assetsPixelsPerUnit * targetHeight;
            ratioTarget = (float)(float)res.height / assetsHeight;
        }
        float ratioTargetOriginal = ratioTarget;

        if (pixelPerfect)
        {
            float ratioSnapped         = Mathf.Ceil(ratioTarget);
            float ratioSnappedPrevious = ratioSnapped - 1;
            // choose the ratio whose fov (or native asset resolution) is nearest to the ratioTarget's fov
            ratioTarget = (1 / ratioTarget - 1 / ratioSnapped < 1 / ratioSnappedPrevious - 1 / ratioTarget) ? ratioSnapped : ratioSnappedPrevious;
            if (ratioSnapped <= 1)
            {
                ratioTarget = 1;
            }
        }

        float ratioHorizontal = 0;
        float ratioVertical   = 0;

        if (maxHorizontalFOV > 0f)
        {
            float assetsWidth = assetsPixelsPerUnit * maxHorizontalFOV;
            ratioHorizontal = (float)res.width / assetsWidth;
        }
        if (maxVerticalFOV > 0f)
        {
            float assetsHeight = assetsPixelsPerUnit * maxVerticalFOV;
            ratioVertical = (float)res.height / assetsHeight;
        }
        float ratioMin = Mathf.Max(ratioHorizontal, ratioVertical);

        if (pixelPerfect)
        {
            ratioMin = Mathf.Ceil(ratioMin);
        }
        float ratioUsed = Mathf.Max(ratioMin, ratioTarget);

        float horizontalFOV = res.width / (assetsPixelsPerUnit * ratioUsed);
        float verticalFOV   = horizontalFOV / AR;

        // ------ GUI Calculations  -----
        this.cameraSize = new Vector2(horizontalFOV / 2, verticalFOV / 2);
        bool unconstrained = ratioTarget >= Mathf.Max(ratioHorizontal, ratioVertical) && ratioTargetOriginal >= Mathf.Max(ratioHorizontal, ratioVertical);

        this.contraintUsed       = (unconstrained) ? ConstraintType.None : (ratioHorizontal > ratioVertical) ? ConstraintType.Horizontal : ConstraintType.Vertical;
        this.cameraPixelsPerUnit = (float)res.width / horizontalFOV;
        this.ratio = ratioUsed;
        this.nativeAssetResolution = new Vector2(horizontalFOV * assetsPixelsPerUnit, verticalFOV * assetsPixelsPerUnit);
        this.fovCoverage           = ratioTargetOriginal / ratioUsed;
        this.isInitialized         = true;
        // ------ GUI Calculations End  -----

        return(verticalFOV / 2);
    }
    void ChosenOne()
    {
        if (chosen.Count != 0)
        {
            ico.GetComponent <Image>().enabled   = true;
            HPtext.GetComponent <Text>().enabled = true;
            物攻.GetComponent <Text>().enabled     = true;
            魔攻.GetComponent <Text>().enabled     = true;
            物防.GetComponent <Text>().enabled     = true;
            魔防.GetComponent <Text>().enabled     = true;
            字.GetComponent <Text>().enabled      = true;
            ico.GetComponent <Image>().sprite    = chosen[0].GetComponent <SpriteRenderer>().sprite;
            HPtext.GetComponent <Text>().text    = chosen[0].GetComponent <BasicUnits>().HP.ToString("0") + "/" + chosen[0].GetComponent <BasicUnits>().maxHp.ToString("0");
            //物攻.GetComponent<Text>().text = "物攻:" + chosen[0].GetComponent<BasicUnits>().phAtk.ToString("0");
            //魔攻.GetComponent<Text>().text = "魔攻:" + chosen[0].GetComponent<BasicUnits>().mgAtk.ToString("0");
            //物防.GetComponent<Text>().text = "物防:" + chosen[0].GetComponent<BasicUnits>().phDef.ToString("0");
            //魔防.GetComponent<Text>().text = "魔防:" + chosen[0].GetComponent<BasicUnits>().mgDef.ToString("0");

            物攻.GetComponent <Text>().text = "Melee ATK:" + chosen[0].GetComponent <BasicUnits>().phAtk.ToString("0");
            魔攻.GetComponent <Text>().text = "Magic ATK:" + chosen[0].GetComponent <BasicUnits>().mgAtk.ToString("0");
            物防.GetComponent <Text>().text = "Melee DEF:" + chosen[0].GetComponent <BasicUnits>().phDef.ToString("0");
            魔防.GetComponent <Text>().text = "Magic DEF:" + chosen[0].GetComponent <BasicUnits>().mgDef.ToString("0");
            if (chosen[0].GetComponent <BasicUnits>().atkMode)
            {
                //物攻.GetComponent<Text>().text = "主物攻:" + chosen[0].GetComponent<BasicUnits>().phAtk.ToString("0");
                物攻.GetComponent <Text>().text = "Main Melee ATK:" + chosen[0].GetComponent <BasicUnits>().phAtk.ToString("0");
            }
            else
            {
                //魔攻.GetComponent<Text>().text = "主魔攻:" + chosen[0].GetComponent<BasicUnits>().mgAtk.ToString("0");
                魔攻.GetComponent <Text>().text = "Main Magic ATK:" + chosen[0].GetComponent <BasicUnits>().mgAtk.ToString("0");
            }
            字.GetComponent <Text>().text = chosen[0].GetComponent <BasicUnits>().name;
            if (chosen[0].GetComponent <skilledUnits>() != null)
            {
                skilledUnits it = chosen[0].GetComponent <skilledUnits>();
                if (it.skill1 != null && it.skill1.isLearned)
                {
                    if (it.skill1.currentCD > 0)
                    {
                        技能[0].GetComponent <Text>().text = it.skill1.name + " " + Mathf.Ceil(it.skill1.currentCD).ToString();
                    }
                    else
                    {
                        技能[0].GetComponent <Text>().text = it.skill1.name;
                    }
                    技能[0].GetComponent <Text>().enabled = true;
                }
                if (it.skill2 != null && it.skill2.isLearned)
                {
                    if (it.skill2.currentCD > 0)
                    {
                        技能[1].GetComponent <Text>().text = it.skill2.name + " " + Mathf.Ceil(it.skill2.currentCD).ToString();
                    }
                    else
                    {
                        技能[1].GetComponent <Text>().text = it.skill2.name;
                    }
                    技能[1].GetComponent <Text>().enabled = true;
                }
                else
                {
                    技能[1].GetComponent <Text>().enabled = false;
                }
                if (it.skill3 != null && it.skill3.isLearned)
                {
                    if (it.skill3.currentCD > 0)
                    {
                        技能[2].GetComponent <Text>().text = it.skill3.name + " " + Mathf.Ceil(it.skill3.currentCD).ToString();
                    }
                    else
                    {
                        技能[2].GetComponent <Text>().text = it.skill3.name;
                    }
                    技能[2].GetComponent <Text>().enabled = true;
                }
                else
                {
                    技能[3].GetComponent <Text>().enabled = false;
                }
                if (it.skill4 != null && it.skill4.isLearned)
                {
                    if (it.skill4.currentCD > 0)
                    {
                        技能[3].GetComponent <Text>().text = it.skill1.name + " " + Mathf.Ceil(it.skill4.currentCD).ToString();
                    }
                    else
                    {
                        技能[3].GetComponent <Text>().text = it.skill1.name;
                    }
                    技能[3].GetComponent <Text>().enabled = true;
                }
                else
                {
                    技能[3].GetComponent <Text>().enabled = false;
                }
            }
            if (chosen[0].GetComponent <Hero>() != null)
            {
                Hero it = chosen[0].GetComponent <Hero>();
                //等级.GetComponent<Text>().text = "等级:" + it.level.ToString();
                等级.GetComponent <Text>().text    = "Level:" + it.level.ToString();
                等级.GetComponent <Text>().enabled = true;
                //经验.GetComponent<Text>().text = "经验:" + it.exp.ToString() + "/" + it.maxExp.ToString();
                经验.GetComponent <Text>().text    = "EXP:" + it.exp.ToString() + "/" + it.maxExp.ToString();
                经验.GetComponent <Text>().enabled = true;
                int all = it.Item.Count;
                if (all != 0)
                {
                    for (int jk = 0; jk < all; jk++)
                    {
                        物品[jk].GetComponent <Text>().enabled = true;
                        if (it.Item[jk].consumable)
                        {
                            物品[jk].GetComponent <Text>().text = it.Item[jk].name + "×" + it.Item[jk].num.ToString();
                        }
                        else
                        {
                            物品[jk].GetComponent <Text>().text = it.Item[jk].name;
                        }
                    }
                    if (all < 5)
                    {
                        for (int jk2 = all; jk2 < 5; jk2++)
                        {
                            物品[jk2].GetComponent <Text>().enabled = false;
                        }
                    }
                }
                else
                {
                    物品[0].GetComponent <Text>().enabled = false;
                    物品[1].GetComponent <Text>().enabled = false;
                    物品[2].GetComponent <Text>().enabled = false;
                    物品[3].GetComponent <Text>().enabled = false;
                    物品[4].GetComponent <Text>().enabled = false;
                }
            }
            else
            {
                等级.GetComponent <Text>().enabled    = false;
                经验.GetComponent <Text>().enabled    = false;
                物品[0].GetComponent <Text>().enabled = false;
                物品[1].GetComponent <Text>().enabled = false;
                物品[2].GetComponent <Text>().enabled = false;
                物品[3].GetComponent <Text>().enabled = false;
                物品[4].GetComponent <Text>().enabled = false;
            }
        }
        else if (enemyChoice != null)
        {
            ico.GetComponent <Image>().enabled   = true;
            HPtext.GetComponent <Text>().enabled = true;
            物攻.GetComponent <Text>().enabled     = true;
            魔攻.GetComponent <Text>().enabled     = true;
            物防.GetComponent <Text>().enabled     = true;
            魔防.GetComponent <Text>().enabled     = true;
            字.GetComponent <Text>().enabled      = true;
            ico.GetComponent <Image>().sprite    = enemyChoice.GetComponent <SpriteRenderer>().sprite;
            HPtext.GetComponent <Text>().text    = enemyChoice.GetComponent <BasicUnits>().HP.ToString() + "/" + enemyChoice.GetComponent <BasicUnits>().maxHp.ToString("0");
            //物攻.GetComponent<Text>().text = "物攻:" + enemyChoice.GetComponent<BasicUnits>().phAtk.ToString("0");
            //魔攻.GetComponent<Text>().text = "魔攻:" + enemyChoice.GetComponent<BasicUnits>().mgAtk.ToString("0");
            物攻.GetComponent <Text>().text = "Melee ATK:" + enemyChoice.GetComponent <BasicUnits>().phAtk.ToString("0");
            魔攻.GetComponent <Text>().text = "Magic ATK:" + enemyChoice.GetComponent <BasicUnits>().mgAtk.ToString("0");
            if (enemyChoice.GetComponent <BasicUnits>().atkMode)
            {
                //物攻.GetComponent<Text>().text = "主物攻:" + enemyChoice.GetComponent<BasicUnits>().phAtk.ToString("0");
                物攻.GetComponent <Text>().text = "Main Melee ATK:" + enemyChoice.GetComponent <BasicUnits>().phAtk.ToString("0");
            }
            else
            {
                //魔攻.GetComponent<Text>().text = "主魔攻:" + enemyChoice.GetComponent<BasicUnits>().mgAtk.ToString("0");
                魔攻.GetComponent <Text>().text = "Main Magic ATK:" + enemyChoice.GetComponent <BasicUnits>().mgAtk.ToString("0");
            }
            //物防.GetComponent<Text>().text = "物防:" + enemyChoice.GetComponent<BasicUnits>().phDef.ToString("0");
            //魔防.GetComponent<Text>().text = "魔防:" + enemyChoice.GetComponent<BasicUnits>().mgDef.ToString("0");
            物防.GetComponent <Text>().text = "Melee DEF:" + enemyChoice.GetComponent <BasicUnits>().phDef.ToString("0");
            魔防.GetComponent <Text>().text = "Magic DEF:" + enemyChoice.GetComponent <BasicUnits>().mgDef.ToString("0");
            字.GetComponent <Text>().text  = enemyChoice.GetComponent <BasicUnits>().name;
            if (enemyChoice.GetComponent <Hero>() != null)
            {
                Hero it = enemyChoice.GetComponent <Hero>();
                //等级.GetComponent<Text>().text = "等级:" + it.level.ToString();
                等级.GetComponent <Text>().text    = "Level:" + it.level.ToString();
                等级.GetComponent <Text>().enabled = true;
            }
            技能[0].GetComponent <Text>().enabled = false;
            技能[1].GetComponent <Text>().enabled = false;
            技能[2].GetComponent <Text>().enabled = false;
            技能[3].GetComponent <Text>().enabled = false;
            物品[0].GetComponent <Text>().enabled = false;
            物品[1].GetComponent <Text>().enabled = false;
            物品[2].GetComponent <Text>().enabled = false;
            物品[3].GetComponent <Text>().enabled = false;
            物品[4].GetComponent <Text>().enabled = false;
        }
        else
        {
            ico.GetComponent <Image>().enabled   = false;
            HPtext.GetComponent <Text>().enabled = false;
            物攻.GetComponent <Text>().enabled     = false;
            魔攻.GetComponent <Text>().enabled     = false;
            物防.GetComponent <Text>().enabled     = false;
            魔防.GetComponent <Text>().enabled     = false;
            等级.GetComponent <Text>().enabled     = false;
            经验.GetComponent <Text>().enabled     = false;
            技能[0].GetComponent <Text>().enabled  = false;
            技能[1].GetComponent <Text>().enabled  = false;
            技能[2].GetComponent <Text>().enabled  = false;
            技能[3].GetComponent <Text>().enabled  = false;
            物品[0].GetComponent <Text>().enabled  = false;
            物品[1].GetComponent <Text>().enabled  = false;
            物品[2].GetComponent <Text>().enabled  = false;
            物品[3].GetComponent <Text>().enabled  = false;
            物品[4].GetComponent <Text>().enabled  = false;
            字.GetComponent <Text>().enabled      = false;
        }
    }
 bool InputBackwards()
 {
     return((ForwardScalar() * Mathf.Ceil(InputManager.HorizontalInput())) < 0);
 }
Beispiel #10
0
 /// <summary>
 /// Set respawn delay value displayed to the absolute time value received.
 /// The remaining time value is calculated in a coroutine by GameManager.
 /// </summary>
 public void SetSpawnDelay(float time)
 {
     spawnDelayText.text = Mathf.Ceil(time) + "";
 }
Beispiel #11
0
 void Update()
 {
     speed.text = Mathf.Ceil(dashboard.carControl.speedObject.speedInKPH) + string.Empty;
 }
Beispiel #12
0
 public float GetRollSeconds()
 {
     rollDuration = Mathf.Ceil(1.0f / rollSpeed * 100.0f) * 0.01f;
     return(rollDelay + rollDuration);
 }
Beispiel #13
0
 void LidarUpdate(ScriptableRenderContext context, Camera[] cameras)
 {
     lidarShader.SetFloat("rayDropProbability", rayDropProbability);
     lidarShader.Dispatch(kernelHandle, (int)Mathf.Ceil((float)NrOfCameras * (float)NrOfLasers * (float)LidarHorisontalRes / 1024.0f), 1, 1);
 }
Beispiel #14
0
 private int getAboveNode(int index)
 {
     return(int.Parse((Mathf.Ceil((index / 2f) - 1)).ToString()));
 }
Beispiel #15
0
    public void Start()
    {
        eraseMode = false;
        down      = false;
        tiles     = new List <GameObject>();
        contour   = new List <GameObject>();
        colors    = new Color[4];
        ColorUtility.TryParseHtmlString("#4285F4", out colors[0]);
        ColorUtility.TryParseHtmlString("#FBBC05", out colors[1]);
        ColorUtility.TryParseHtmlString("#EA4335", out colors[2]);
        ColorUtility.TryParseHtmlString("#34A853", out colors[3]);
        palette = GameObject.FindObjectOfType <PaletteBT>();

        palette.ColorCount = 2; // It must be taken from Puzzle


        int toolbarScenario = 0;

        if (toolbarMode)
        {
            toolbarScenario = Screen.height / 10;
        }

        puzzleString = puzzleString.Replace(' ', '\n');

        currentPuzzle = new PuzzleBT("bb0bb00b0001b011b111bb1b", 2, 4, 6, false, false);
        currentPuzzle.Clear();

        cols = currentPuzzle.width;
        rows = currentPuzzle.height;


        tileMargin = (int)Mathf.Ceil(Screen.width / 720.0f);

        verticalFieldMargin = tileMargin; //Screen.width * 5 / 180;

        fieldHeight = Screen.height - 2 * verticalFieldMargin - Screen.width / 5 - toolbarScenario;

        tileSize = Mathf.Min((fieldHeight - 2 * tileMargin * rows) / rows, (Screen.width - 2 * tileMargin * cols) / cols);

        int centringTop  = (fieldHeight - rows * (tileSize + 2 * tileMargin)) / 2;
        int centringLeft = (Screen.width - cols * (tileSize + 2 * tileMargin)) / 2;

        TextGameMas = new GameObject[(rows) * cols + (cols) - 1];
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                int index = i * cols + j;

                int X = centringLeft + tileMargin + j * (tileSize + 2 * tileMargin);
                int Y = Screen.height - toolbarScenario - centringTop - verticalFieldMargin - tileMargin - i * (tileSize + 2 * tileMargin);

                tiles.Add(Instantiate(tile, new Vector3(X, Y, 0), Quaternion.identity) as GameObject);
                tiles[index].transform.SetParent(gameField.transform, true);

                tiles[index].GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, tileSize);
                tiles[index].GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, tileSize);
                switch (currentPuzzle[i, j])
                {
                case 'b': tiles[index].GetComponent <Image>().color = Color.clear; break;

                case 'e': tiles[index].GetComponent <Image>().color = Color.white; break;
                }

                EventTrigger trigger = tiles[index].GetComponent <EventTrigger>();

                EventTrigger.Entry entry = new EventTrigger.Entry();
                entry.eventID = EventTriggerType.PointerDown;
                entry.callback.AddListener(delegate { TileDown(index); });
                trigger.triggers.Add(entry);

                entry         = new EventTrigger.Entry();
                entry.eventID = EventTriggerType.PointerEnter;
                entry.callback.AddListener(delegate { TileHover(index); });
                trigger.triggers.Add(entry);

                if (tiles[index].GetComponent <Image>().color == Color.white)
                {
                    TextCreator(index);
                }
            }
        }
    }
Beispiel #16
0
 public float GetRemainingHealth()
 {
     return(Mathf.Ceil(remainingHP));
 }
    private Queue <BehaviourWeight> CalculateBehaviours(LocalPlayerController player)
    {
        // Queue of selected behaviour names.
        Queue <string>          selectedBehaviourNames = new Queue <string>();
        Queue <BehaviourWeight> selectedBehaviours     = new Queue <BehaviourWeight>();

        // Total weight to distribute at the start of generating behaviours.
        float totalWeight = currentBaseWeaponWeight * player.weaponWeightScalar;

        Debug.Log("Player #" + player.playerIndex + " - Behaviours Weight: " + totalWeight);

        int increments = 0;

        // Get a list of all behaviours within the player's weight range.
        List <BehaviourWeight> remainingBehaviours = GetListOfPossibleBehaviours(totalWeight);

        // Loop until all behaviours are maxed out or until totalWeight is depleted.
        while (remainingBehaviours.Count > 0 && totalWeight > 0)
        {
            // Get a random behaviour to assign weights to.
            BehaviourWeight currentBehaviour = (BehaviourWeight)GetBiasedVariable(remainingBehaviours.ToArray());

            float weightForValue;

            // If the weight is too low to distribute with random, just assign the remaining weight.
            if (totalWeight > 0.3f)
            {
                // Assign random weight.
                // TODO: experiment with different dividers here.
                weightForValue = UnityEngine.Random.Range(0, totalWeight / 2);
            }
            else
            {
                // Assign left over value.
                weightForValue = totalWeight;

                // Divide leftover weight in unenqueued behaviours over enqueued behaviours,
                // to prevent having a bunch of weight sitting unused in unenqueued behaviours.
                for (int i = remainingBehaviours.Count - 1; i > -1; i--)
                {
                    if (!remainingBehaviours[i].enqueued)
                    {
                        totalWeight += remainingBehaviours[i].currentValue;
                        remainingBehaviours[i].currentValue = 0;
                        remainingBehaviours.Remove(remainingBehaviours[i]);
                    }
                }

                // If we removed all behaviours, redo loop with remaining behaviours
                // that could reach their threshold.
                if (remainingBehaviours.Count == 0)
                {
                    remainingBehaviours = GetListOfPossibleBehaviours(totalWeight);
                }
            }

            // If this is an integer value, round to top to prevent getting stuck.
            if (currentBehaviour.isIntegerValue)
            {
                weightForValue = Mathf.Ceil(weightForValue);
            }

            // Assign the new weight to the dictionary entry to link later to the behaviour.
            currentBehaviour.currentValue += weightForValue;

            // When the value is higher than its max.
            if (currentBehaviour.currentValue > currentBehaviour.maxedWeight)
            {
                // Subtract the difference so it can be spent on other variables.
                float difference = currentBehaviour.currentValue - currentBehaviour.maxedWeight;
                weightForValue -= difference;
                // Clamp to max value.
                currentBehaviour.currentValue = currentBehaviour.maxedWeight;
                // Remove the current selected value from the remaining values so it won't be selected again.
                remainingBehaviours.Remove(currentBehaviour);
            }

            // Adjust the total weight left to distribute.
            totalWeight -= weightForValue;

            // Make sure the current behaviour isn't already enqueued.
            if (!currentBehaviour.enqueued)
            {
                // If the current behaviour has reached its threshold value, enqueue it
                // in the queue of selected behaviours.
                if (currentBehaviour.currentValue >= currentBehaviour.thresholdWeight)
                {
                    selectedBehaviourNames.Enqueue(currentBehaviour.variableName);
                    currentBehaviour.enqueued = true;
                }
            }

            if (increments > 1000)
            {
                Debug.LogError("Something went terribly wrong, leading to far too many loops in CalculateBehaviours().");
                break;
            }
            increments++;
        }

        Debug.Log("Finished behaviour distribution after: " + increments + " increments");

        // Generate queue of actual behaviours from the queue of behaviour names.
        while (selectedBehaviourNames.Count > 0)
        {
            selectedBehaviours.Enqueue(weaponBehaviourDict[selectedBehaviourNames.Dequeue()]);
        }

        // Return queue of selected behaviours.
        return(selectedBehaviours);
    }
Beispiel #18
0
    void FixedUpdate()
    {
        if (_mouseOverInfo != null && _mouseOverPiece != null)
        {
            _mouseOverInfo.SetPosition(_mouseOverPiece.transform.position);
        }

        if (_replay)
        {
            if (_gameOver)
            {
                _gameOverTimer += Time.deltaTime;
                if (_gameOverTimer >= GAME_OVER_TIME)
                {
                    enabled = false;
                    LoadingAlert.Present();
                    PlayerPrefs.SetString("LAST_GAME_VIEWED", OnlineManager.Instance.GameData.id);
                    //Debug.Log("saved game id " + OnlineManager.Instance.GameData.id);
                    PlayerPrefs.Save();
                    ActivateResultsView();
                }
            }
            else
            {
                if (_countdown)
                {
                    _countdownTimer -= Time.deltaTime;
                    if (_countdownTimer < 0.0f)
                    {
                        UIViewController.DeactivateUIView("CountdownView");
                        _countdown = false;
                        //Debug.Log("here!");
                    }
                    else
                    {
                        int count = (int)Mathf.Ceil(_countdownTimer);
                        CountdownText.Text = count.ToString();
                    }
                }
                else
                {
                    if (_replayWatcherInfo != null)
                    {
                        _replayWatcherInfo.SetPosition(_replayWatcherPiece.transform.position);
                        //SetWatcherInfoPosition();
                    }

                    TurnData turnData = DataRecorder.Instance.TurnDataList[_replayIndex];
                    ReplayTurn(turnData);
                    _replayIndex++;

                    // game over
                    if (_gameOver)
                    {
                        _gameOverTimer += Time.deltaTime;
                        if (_gameOverTimer >= GAME_OVER_TIME)
                        {
                            if (_mouseOverInfo != null)
                            {
                                Destroy(_mouseOverInfo.gameObject);
                            }
                            enabled = false;
                            LoadingAlert.Present();
                            PlayerPrefs.SetString("LAST_GAME_VIEWED", OnlineManager.Instance.GameData.id);
                            //Debug.Log("saved game id " + OnlineManager.Instance.GameData.id);
                            PlayerPrefs.Save();
                            ActivateResultsView();
                        }
                    }
                    else if (_replayIndex >= DataRecorder.Instance.TurnDataList.Count)
                    {
                        if (_replayWatcherInfo != null)
                        {
                            Destroy(_replayWatcherInfo.gameObject);
                        }
                        if (_mouseOverInfo != null)
                        {
                            Destroy(_mouseOverInfo.gameObject);
                        }
                        _redTeam.StopPieceAnimations();
                        _blueTeam.StopPieceAnimations();
                        _gameOver      = true;
                        _gameOverTimer = 0.0f;
                    }
                }
            }
        }
        else
        {
            if (_gameOver)
            {
                _gameOverTimer += Time.deltaTime;
                if (_gameOverTimer >= GAME_OVER_TIME)
                {
                    enabled = false;
                    LoadingAlert.Present();
                    _gameTime = DateTime.UtcNow - _startTime;
                    _redTeam.CalulateMVPs();
                    _blueTeam.CalulateMVPs();
                    DisplayGameResults();
                }
            }
            else
            {
#if SLOW_MOTION
                if (Input.GetKey(KeyCode.A))
#endif
                {
                    StartTurn(Time.deltaTime);
                    Attack(Time.deltaTime);
                    RecordMoves();
                    RemoveDoneBalloons();
                    if (CheckGameOver())
                    {
                        _redTeam.StopPieceAnimations();
                        _blueTeam.StopPieceAnimations();
                        SoundManager.Instance.PlaySoundEffect(SoundType.CHEER);
                        _gameOver      = true;
                        _gameOverTimer = 0.0f;
                    }
                }
            }
        }
    }
Beispiel #19
0
    protected virtual void Update()
    {
        if ((isDraggingObject && !Input.GetMouseButton(0)) || (isDraggingObjectAtTime && !Input.GetMouseButton(1)))
        {
            noteGridTransform.localPosition = new Vector3(noteGridTransform.localPosition.x, noteGridTransform.localPosition.y, 0);
            FinishDrag();
        }
        if (Application.isFocused != applicationFocus)
        {
            applicationFocus        = Application.isFocused;
            applicationFocusChanged = true;
            return;
        }
        else if (applicationFocusChanged)
        {
            applicationFocusChanged = false;
        }
        Ray ray = mainCamera.ScreenPointToRay(mousePosition);

        RaycastHit[] BeatmapObjectsHit = Physics.RaycastAll(ray, 999f);
        isOnPlacement = false;
        foreach (RaycastHit objectHit in BeatmapObjectsHit)
        {
            if (!isOnPlacement && objectHit.transform.GetComponentInParent(GetType()) != null)
            {
                isOnPlacement = true;
                break;
            }
        }
        if (PauseManager.IsPaused)
        {
            return;
        }
        if ((!IsValid && ((!isDraggingObject && !isDraggingObjectAtTime) || !IsActive)) || !isOnPlacement)
        {
            ColliderExit();
            return;
        }
        if (instantiatedContainer == null)
        {
            RefreshVisuals();
        }
        if (!instantiatedContainer.gameObject.activeSelf)
        {
            instantiatedContainer.gameObject.SetActive(true);
        }
        objectData = queuedData;
        if (Physics.Raycast(ray, out RaycastHit hit, 999f, 1 << 11))
        {
            Transform hitTransform = hit.transform; //Make a reference to the transform instead of calling hit.transform a lot
            if (!hitTransform.IsChildOf(transform) || hitTransform.GetComponent <PlacementMessageSender>() == null ||
                PersistentUI.Instance.DialogBox_IsEnabled)
            {
                ColliderExit();
                return;
            }
            if (customStandaloneInputModule.IsPointerOverGameObject <GraphicRaycaster>(-1, true))
            {
                return;
            }
            if (BeatmapObjectContainerCollection.TrackFilterID != null && !objectContainerCollection.IgnoreTrackFilter)
            {
                queuedData.GetOrCreateCustomData()["track"] = BeatmapObjectContainerCollection.TrackFilterID;
            }
            else
            {
                queuedData?._customData?.Remove("track");
            }
            CalculateTimes(hit, out Vector3 roundedHit, out float roundedTime);
            RoundedTime = roundedTime;
            float placementZ = RoundedTime * EditorScaleController.EditorScale;
            Update360Tracks();

            //this mess of localposition and position assignments are to align the shits up with the grid
            //and to hopefully not cause IndexOutOfRangeExceptions
            instantiatedContainer.transform.localPosition = parentTrack.InverseTransformPoint(hit.point); //f**k transformedpoint we're doing it ourselves

            Vector3 localMax       = parentTrack.InverseTransformPoint(hit.collider.bounds.max);
            Vector3 localMin       = parentTrack.InverseTransformPoint(hit.collider.bounds.min);
            float   farRightPoint  = PlacementXMax;
            float   farLeftPoint   = PlacementXMin;
            float   farTopPoint    = localMax.y;
            float   farBottomPoint = localMin.y;

            roundedHit = new Vector3(Mathf.Ceil(roundedHit.x), Mathf.Ceil(roundedHit.y), placementZ);
            instantiatedContainer.transform.localPosition = roundedHit - new Vector3(0.5f, 1f, 0);
            float x = instantiatedContainer.transform.localPosition.x; //Clamp values to prevent exceptions
            float y = instantiatedContainer.transform.localPosition.y;
            instantiatedContainer.transform.localPosition = new Vector3(
                Mathf.Clamp(x, farLeftPoint + 0.5f, farRightPoint - 0.5f),
                Mathf.Round(Mathf.Clamp(y, farBottomPoint, farTopPoint - 1)) + 0.5f,
                instantiatedContainer.transform.localPosition.z);

            if (!hit.collider.gameObject.name.Contains("Grid X"))
            {
                instantiatedContainer.transform.localPosition += new Vector3(0, 1f, 0);
            }

            OnPhysicsRaycast(hit, roundedHit);
            queuedData._time = RoundedTime;
            if ((isDraggingObject || isDraggingObjectAtTime) && queuedData != null)
            {
                TransferQueuedToDraggedObject(ref draggedObjectData, BeatmapObject.GenerateCopy(queuedData));
                draggedObjectContainer.objectData._time = placementZ / EditorScaleController.EditorScale;
                if (draggedObjectContainer != null)
                {
                    draggedObjectContainer.UpdateGridPosition();
                }
            }
        }
    internal virtual void Update()
    {
        if (KeybindsController.AltHeld && Input.GetMouseButtonDown(0) && CanClickAndDrag)
        {
            Ray dragRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(dragRay, out RaycastHit dragHit, 999f, 1 << 9))
            {
                BeatmapObjectContainer con = dragHit.transform.gameObject.GetComponent <BeatmapObjectContainer>();
                if (con is null || !(con is BOC))
                {
                    return;                               //Filter out null objects and objects that aren't what we're targetting.
                }
                isDraggingObject       = true;
                draggedObjectData      = BeatmapObject.GenerateCopy(con.objectData as BO);
                originalQueued         = BeatmapObject.GenerateCopy(queuedData);
                queuedData             = BeatmapObject.GenerateCopy(draggedObjectData);
                draggedObjectContainer = con as BOC;
                return;
            }
        }
        else if ((!KeybindsController.AltHeld || Input.GetMouseButtonUp(0)) && isDraggingObject)
        {
            isDraggingObject = false;
            queuedData       = BeatmapObject.GenerateCopy(originalQueued);
        }
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        RaycastHit[] BeatmapObjectsHit = Physics.RaycastAll(ray, 999f);
        bool         isOnPlacement     = false;

        foreach (RaycastHit objectHit in BeatmapObjectsHit)
        {
            if (objectHit.transform.GetComponentsInParent(GetType()).Any() && !isOnPlacement)
            {
                isOnPlacement = true;
            }
            BeatmapObjectContainer con = objectHit.transform.gameObject.GetComponent <BeatmapObjectContainer>();
            if (con == null || con == draggedObjectContainer)
            {
                continue;
            }
            con.SafeSetBoxCollider(KeybindsController.AnyCriticalKeys || Input.GetMouseButtonDown(2));
        }
        if (PauseManager.IsPaused)
        {
            return;
        }
        if ((!IsValid && (!isDraggingObject || !IsActive)) || !isOnPlacement)
        {
            ColliderExit();
            return;
        }
        if (instantiatedContainer == null)
        {
            RefreshVisuals();
        }
        if (!instantiatedContainer.gameObject.activeSelf)
        {
            instantiatedContainer.gameObject.SetActive(true);
        }
        objectData = queuedData;
        if (Physics.Raycast(ray, out RaycastHit hit, 999f, 1 << 11))
        {
            if (customStandaloneInputModule.IsPointerOverGameObject <GraphicRaycaster>(-1, true))
            {
                return;
            }
            if (BeatmapObjectContainerCollection.TrackFilterID != null && !objectContainerCollection.IgnoreTrackFilter)
            {
                if (queuedData._customData == null)
                {
                    queuedData._customData = new SimpleJSON.JSONObject();
                }
                queuedData._customData["track"] = BeatmapObjectContainerCollection.TrackFilterID;
            }
            else
            {
                queuedData?._customData?.Remove("track");
            }
            float snapping       = 1f / atsc.gridMeasureSnapping;
            float time           = (hit.point.z / EditorScaleController.EditorScale) + atsc.CurrentBeat;
            float roundedTime    = (Mathf.Round((time - atsc.offsetBeat) / snapping) * snapping) + atsc.offsetBeat;
            float roundedCurrent = Mathf.Round(atsc.CurrentBeat / snapping) * snapping;
            float offsetTime     = hit.collider.gameObject.name.Contains("Interface") ? 0 : atsc.CurrentBeat - roundedCurrent;
            if (!atsc.IsPlaying)
            {
                roundedTime += offsetTime;
            }
            RoundedTime = roundedTime;
            float placementZ = roundedTime * EditorScaleController.EditorScale;
            instantiatedContainer.transform.localPosition = new Vector3(
                Mathf.Clamp(Mathf.Ceil(hit.point.x + 0.1f),
                            Mathf.Ceil(hit.collider.bounds.min.x),
                            Mathf.Floor(hit.collider.bounds.max.x)
                            ) - 0.5f,
                Mathf.Clamp(Mathf.Floor(hit.point.y - 0.1f), 0f,
                            Mathf.Floor(hit.collider.bounds.max.y)) + 0.5f,
                placementZ
                );
            OnPhysicsRaycast(hit);
            if (isDraggingObject && queuedData != null)
            {
                TransferQueuedToDraggedObject(ref draggedObjectData, BeatmapObject.GenerateCopy(queuedData));
                draggedObjectContainer.objectData       = draggedObjectData;
                draggedObjectContainer.objectData._time = placementZ / EditorScaleController.EditorScale;
                draggedObjectContainer.UpdateGridPosition();
            }
        }
        if (Input.GetMouseButtonDown(0) && !isDraggingObject)
        {
            ApplyToMap();
        }
    }
Beispiel #21
0
 public void SetHealthUI()
 {
     healthSlider.value = CalculateHealthPercentage();
     healthText.text    = Mathf.Ceil(health).ToString() + " / " + Mathf.Ceil(maxHealth).ToString();
 }
    void Update()
    {
        if (_transforms == null)
        {
            return;
        }

        if (_transforms.Length < 2)
        {
            return;
        }

        if (_emit && _emitTime != 0)
        {
            _emitTime -= Time.deltaTime;
            if (_emitTime == 0)
            {
                _emitTime = -1;
            }
            if (_emitTime < 0)
            {
                _emit = false;
            }
        }

        if (!_emit && _points.Count == 0 && _autoDestruct)
        {
            Destroy(_trailObject);
            Destroy(gameObject);
        }

        // early out if there is no camera
        if (!Camera.main)
        {
            return;
        }

        // if we have moved enough, create a new vertex and make sure we rebuild the mesh
        float theDistanceSqr = (_lastPosition - transform.position).sqrMagnitude;

        if (_emit)
        {
            if (theDistanceSqr > _minVertexDistanceSqr)
            {
                bool make = false;
                if (_points.Count < 3)
                {
                    make = true;
                }
                else
                {
                    //Vector3 l1 = _points[_points.Count - 2].basePosition - _points[_points.Count - 3].basePosition;
                    //Vector3 l2 = _points[_points.Count - 1].basePosition - _points[_points.Count - 2].basePosition;
                    Vector3 l1 = _points[_points.Count - 2].allVectors[0] - _points[_points.Count - 3].allVectors[0];
                    Vector3 l2 = _points[_points.Count - 1].allVectors[0] - _points[_points.Count - 2].allVectors[0];
                    if (Vector3.Angle(l1, l2) > _maxAngle || theDistanceSqr > _maxVertexDistanceSqr)
                    {
                        make = true;
                    }
                }

                if (make)
                {
                    Point p = new Point();
                    //p.allVectors.Clear();
                    for (int i = 0; i < _transforms.Length; ++i)
                    {
                        p.allVectors.Add(_transforms[i].position);
                    }
                    p.timeCreated = Time.time;
                    _points.Add(p);
                    _lastPosition = transform.position;

#if USE_INTERPOLATION
                    if (_points.Count == 1)
                    {
                        _smoothedPoints.Add(p);
                    }
                    else if (_points.Count > 1)
                    {
                        // add 1+subdivisions for every possible pair in the _points
                        for (int n = 0; n < 1 + subdivisions; ++n)
                        {
                            _smoothedPoints.Add(p);
                        }
                    }

                    // we use 4 control points for the smoothing
                    if (_points.Count >= 4)
                    {
                        List <List <Vector3> > vecsmooths = new List <List <Vector3> >();
                        int transformsSize     = _points[_points.Count - 4].allVectors.Count;
                        int smoothTipListCount = 0;
                        for (int i = 0; i < transformsSize; ++i)
                        {
                            //Debug.LogError( "transformsSize" + transformsSize );
                            Vector3[] tipPoints = new Vector3[4];
                            tipPoints[0] = _points[_points.Count - 4].allVectors[i];
                            tipPoints[1] = _points[_points.Count - 3].allVectors[i];
                            tipPoints[2] = _points[_points.Count - 2].allVectors[i];
                            tipPoints[3] = _points[_points.Count - 1].allVectors[i];

                            /// donot use Bezier  HelloHuan;
                            //IEnumerable<Vector3> smoothTip = Interpolate.NewBezier(Interpolate.Ease(Interpolate.EaseType.Linear), tipPoints, subdivisions);
                            IEnumerable <Vector3> smoothTip = Interpolate.NewCatmullRom(tipPoints, subdivisions, false);

                            List <Vector3> Tmp = new List <Vector3>(smoothTip);
                            smoothTipListCount = Tmp.Count;
                            //Debug.LogError( "smoothTipListCount\t\t" + smoothTipListCount );
                            vecsmooths.Add(Tmp);
                        }

                        float firstTime  = _points[_points.Count - 4].timeCreated;
                        float secondTime = _points[_points.Count - 1].timeCreated;

                        //Debug.Log(" smoothTipList.Count: " + smoothTipList.Count);
                        for (int n = 0; n < smoothTipListCount; ++n)
                        {
                            int idx = _smoothedPoints.Count - (smoothTipListCount - n);
                            // there are moments when the _smoothedPoints are lesser
                            // than what is required, when elements from it are removed
                            if (idx > -1 && idx < _smoothedPoints.Count)
                            {
                                Point sp = new Point();

                                for (int i = 0; i < transformsSize; ++i)
                                {
                                    sp.allVectors.Add(vecsmooths[i][n]);
                                }
                                sp.timeCreated       = Mathf.Lerp(firstTime, secondTime, (float)n / smoothTipListCount);
                                _smoothedPoints[idx] = sp;
                            }
                            //else
                            //{
                            //	Debug.LogError(idx + "/" + _smoothedPoints.Count);
                            //}
                        }
                    }
#endif
                }
                else
                {
                    if (_points[_points.Count - 1].allVectors.Count == _transforms.Length)
                    {
                        for (int i = 0; i < _transforms.Length; ++i)
                        {
                            _points[_points.Count - 1].allVectors[i] = (_transforms[i].position);
                        }
                    }
                    else
                    {
                        _points[_points.Count - 1].RemoveVectors();
                        for (int i = 0; i < _transforms.Length; ++i)
                        {
                            _points[_points.Count - 1].allVectors.Add(_transforms[i].position);
                        }
                    }

                    //_points[_points.Count - 1].timeCreated = Time.time;

#if USE_INTERPOLATION
//					_smoothedPoints[_smoothedPoints.Count - 1].RemoveVectors();
//					for(int i = 0; i < _transforms.Length; ++i)
//					{
//						_smoothedPoints[_smoothedPoints.Count - 1].allVectors.Add(_transforms[i].position);
//					}

                    if (_smoothedPoints[_smoothedPoints.Count - 1].allVectors.Count == _transforms.Length)
                    {
                        for (int i = 0; i < _transforms.Length; ++i)
                        {
                            _smoothedPoints[_smoothedPoints.Count - 1].allVectors[i] = (_transforms[i].position);
                        }
                    }
                    else
                    {
                        _smoothedPoints[_smoothedPoints.Count - 1].RemoveVectors();
                        for (int i = 0; i < _transforms.Length; ++i)
                        {
                            _smoothedPoints[_smoothedPoints.Count - 1].allVectors.Add(_transforms[i].position);
                        }
                    }
                                        #endif
                }
            }
            else
            {
                if (_points.Count > 0)
                {
//					for(int i = 0; i < _transforms.Length; ++i)
//					{
//						_points[_points.Count - 1].allVectors.Add(_transforms[i].position);
//					}
                    if (_points[_points.Count - 1].allVectors.Count == _transforms.Length)
                    {
                        for (int i = 0; i < _transforms.Length; ++i)
                        {
                            _points[_points.Count - 1].allVectors[i] = (_transforms[i].position);
                        }
                    }
                    else
                    {
                        _points[_points.Count - 1].RemoveVectors();
                        for (int i = 0; i < _transforms.Length; ++i)
                        {
                            _points[_points.Count - 1].allVectors.Add(_transforms[i].position);
                        }
                    }
                    //_points[_points.Count - 1].timeCreated = Time.time;
                }

#if USE_INTERPOLATION
                if (_smoothedPoints.Count > 0)
                {
//					for(int i = 0; i < _transforms.Length; ++i)
//					{
//						_smoothedPoints[_smoothedPoints.Count - 1].allVectors.Add(_transforms[i].position);
//					}
                    if (_smoothedPoints[_smoothedPoints.Count - 1].allVectors.Count == _transforms.Length)
                    {
                        for (int i = 0; i < _transforms.Length; ++i)
                        {
                            _smoothedPoints[_smoothedPoints.Count - 1].allVectors[i] = (_transforms[i].position);
                        }
                    }
                    else
                    {
                        _smoothedPoints[_smoothedPoints.Count - 1].RemoveVectors();
                        for (int i = 0; i < _transforms.Length; ++i)
                        {
                            _smoothedPoints[_smoothedPoints.Count - 1].allVectors.Add(_transforms[i].position);
                        }
                    }
                }
#endif
            }
        }

        RemoveOldPoints(_points);
        if (_points.Count == 0)
        {
            _trailMesh.Clear();
        }

#if USE_INTERPOLATION
        RemoveOldPoints(_smoothedPoints);
        if (_smoothedPoints.Count == 0)
        {
            _trailMesh.Clear();
        }
#endif


#if USE_INTERPOLATION
        List <Point> pointsToUse = _smoothedPoints;
#else
        List <Point> pointsToUse = _points;
#endif

        if (pointsToUse.Count > 1)
        {
            int       sectionPointSize = _transforms.Length;
            Vector3[] newVertices      = new Vector3[pointsToUse.Count * sectionPointSize];
            Vector2[] newUV            = new Vector2[pointsToUse.Count * sectionPointSize];
            int[]     newTriangles     = new int[(pointsToUse.Count - 1) * 6 * (sectionPointSize - 1)];
            Color[]   newColors        = new Color[pointsToUse.Count * sectionPointSize];

            for (int n = 0; n < pointsToUse.Count; ++n)
            {
                Point p    = pointsToUse[n];
                float time = (Time.time - p.timeCreated) / _lifeTime;

                Color color = Color.Lerp(Color.white, Color.clear, time);
                if (_colors != null && _colors.Length > 0)
                {
                    float colorTime = time * (_colors.Length - 1);
                    float min       = Mathf.Floor(colorTime);
                    float max       = Mathf.Clamp(Mathf.Ceil(colorTime), 1, _colors.Length - 1);
                    float lerp      = Mathf.InverseLerp(min, max, colorTime);
                    if (min >= _colors.Length)
                    {
                        min = _colors.Length - 1;
                    }
                    if (min < 0)
                    {
                        min = 0;
                    }
                    if (max >= _colors.Length)
                    {
                        max = _colors.Length - 1;
                    }
                    if (max < 0)
                    {
                        max = 0;
                    }
                    color = Color.Lerp(_colors[(int)min], _colors[(int)max], lerp);
                }

                float size = 0f;
                if (_sizes != null && _sizes.Length > 0)
                {
                    float sizeTime = time * (_sizes.Length - 1);
                    float min      = Mathf.Floor(sizeTime);
                    float max      = Mathf.Clamp(Mathf.Ceil(sizeTime), 1, _sizes.Length - 1);
                    float lerp     = Mathf.InverseLerp(min, max, sizeTime);
                    if (min >= _sizes.Length)
                    {
                        min = _sizes.Length - 1;
                    }
                    if (min < 0)
                    {
                        min = 0;
                    }
                    if (max >= _sizes.Length)
                    {
                        max = _sizes.Length - 1;
                    }
                    if (max < 0)
                    {
                        max = 0;
                    }
                    size = Mathf.Lerp(_sizes[(int)min], _sizes[(int)max], lerp);
                }

                Vector3 lineDirection = p.allVectors[sectionPointSize - 1] - p.allVectors[0];
                //newVertices[n * 2] = p.basePosition - (lineDirection * (size * 0.5f));
                //newVertices[(n * 2) + 1] = p.tipPosition + (lineDirection * (size * 0.5f));

                float deltaRatioxx = 1.0F / (sectionPointSize - 1);
                float uvRatio      = (float)n / pointsToUse.Count;
                for (int i = 0; i < sectionPointSize; ++i)
                {
                    newVertices[n * sectionPointSize + i] = p.allVectors[i] + (lineDirection * (size * ((deltaRatioxx * i) - 0.5f)));
                    newColors[(n * sectionPointSize) + i] = color;
                    newUV[(n * sectionPointSize) + i]     = new Vector2(uvRatio, deltaRatioxx * i);
                }
                if (n > 0)
                {
                    int triCount   = (sectionPointSize - 1) * 2;
                    int indexCount = triCount * 3;

                    for (int k = 0; k < sectionPointSize - 1; ++k)
                    {
                        newTriangles[(n - 1) * indexCount + 0 + 6 * k]   = ((n - 1) * sectionPointSize) + k;
                        newTriangles[((n - 1) * indexCount) + 1 + 6 * k] = ((n - 1) * sectionPointSize) + 1 + k;
                        newTriangles[((n - 1) * indexCount) + 2 + 6 * k] = (n * sectionPointSize) + k;

                        newTriangles[((n - 1) * indexCount) + 3 + 6 * k] = (n * sectionPointSize) + 1 + k;
                        newTriangles[((n - 1) * indexCount) + 4 + 6 * k] = (n * sectionPointSize) + 0 + k;
                        newTriangles[((n - 1) * indexCount) + 5 + 6 * k] = ((n - 1) * sectionPointSize) + 1 + k;
                    }
                }
            }

            _trailMesh.Clear();
            _trailMesh.vertices  = newVertices;
            _trailMesh.colors    = newColors;
            _trailMesh.uv        = newUV;
            _trailMesh.triangles = newTriangles;
            if (_trailObject != null)
            {
                _trailObject.GetComponent <Renderer>().material.SetColor("_TintColor", _colors[0]);
                _trailObject.GetComponent <Renderer>().material.SetFloat("_Alpha", 0.5f);
            }
        }
    }
Beispiel #23
0
    void createWave()
    {
        typesOfEnnemies = (int)Mathf.Ceil(waveNumber / 3.0f);
        if (typesOfEnnemies > ennemies.Count)
        {
            typesOfEnnemies = ennemies.Count;
        }
        ennemyLevel = (int)Mathf.Ceil(waveNumber / 5);
        List <int> groupRes = new List <int>();

        for (int i = 0; i < typesOfEnnemies; i++)
        {
            int amount     = ennemies[i].GetComponent <colony>().amount;
            int maxGroupNb = ennemies[i].GetComponent <colony>().maxGroupNb;
            amount += (ennemies[i].GetComponent <colony>().amountPerLevel *(ennemyLevel));
            Vector2    randPos = getRandSpawnPoint();
            GameObject createdEnnemy;

            for (int j = 0; j < amount; j++)
            {
                if (j % maxGroupNb == 0 && j > 0)
                {
                    randPos = getRandSpawnPoint();
                }
                createdEnnemy = createEnnemy(ennemies[i], new Vector2(randPos.x + (j * 0.1f), randPos.y + (j * 0.1f)));
                if (j % maxGroupNb == 0)
                {
                    userInterface.GetComponent <UserInterface>().showWarning(createdEnnemy, false);
                }
                if (j == 0)
                {
                    bonusMoney[ennemies[i].tag] = createdEnnemy.GetComponent <colony>().bonusForGroup;
                }
            }
        }
        if (waveNumber % 5 == 0)
        {
            int amount     = bosses[currentBoss].GetComponent <colony>().amount;
            int maxGroupNb = bosses[currentBoss].GetComponent <colony>().maxGroupNb;
            amount += (bosses[currentBoss].GetComponent <colony>().amountPerLevel *(ennemyLevel));
            Vector2    randPos = getRandSpawnPoint();
            GameObject createdEnnemy;
            for (int j = 0; j < amount; j++)
            {
                if (j % maxGroupNb == 0 && j > 0)
                {
                    randPos = getRandSpawnPoint();
                }
                GameObject gO = (GameObject)Instantiate(bosses[currentBoss], new Vector2(randPos.x + (j * 0.1f), randPos.y + (j * 0.1f)), Quaternion.identity);
                gO.GetComponent <colony>().setVariables(gameManager, center, gameObject, userInterface, colors);
                gO.GetComponent <colony>().startingStats(ennemyLevel);
                userInterface.GetComponent <UserInterface>().showWarning(gO, true);
            }
            currentBoss++;
            if (currentBoss >= bosses.Count)
            {
                currentBoss = 0;
            }
        }

        if (waveNumber > 10)
        {
            antibios.transform.GetChild(3).GetComponent <Image>().color = colors[3];
        }
        else if (waveNumber > 6)
        {
            antibios.transform.GetChild(2).GetComponent <Image>().color = colors[2];
        }
        else if (waveNumber > 1)
        {
            antibios.transform.GetChild(1).GetComponent <Image>().color = colors[1];
        }
        soundManager.PlayOneShot(sounds[1]);
    }
Beispiel #24
0
    /// <summary>
    /// 物件的大小加上行距
    /// </summary>
    public void ChangeHight()
    {
        float itemHight = grid.spacing.y + grid.cellSize.y;

        rectTran.sizeDelta = new Vector2(0, itemHight * Mathf.Ceil((float)currentItemNum / grid.constraintCount));//设置高度是几倍行距+自身距离
    }
        public static bool Prefix(InteractableSentry __instance)
        {
            RocketPlayer ownerPlayer = new RocketPlayer(__instance.owner.ToString());

            bool            hasWeapon    = (bool)hasWeaponField.GetValue(__instance);
            bool            isFiring     = (bool)isFiringField.GetValue(__instance);
            bool            isAiming     = (bool)isAimingField.GetValue(__instance);
            float           lastScan     = (float)lastScanField.GetValue(__instance);
            float           lastFire     = (float)lastFireField.GetValue(__instance);
            float           fireTime     = (float)fireTimeField.GetValue(__instance);
            float           lastAim      = (float)lastAimField.GetValue(__instance);
            ItemWeaponAsset displayAsset = displayAssetField.GetValue(__instance) as ItemWeaponAsset;
            Attachments     attachments  = attachmentsField.GetValue(__instance) as Attachments;

            bool interact = (bool)interactField.GetValue(__instance);

            var playersInRadius = (List <Player>)playersInRadiusField.GetValue(null);
            var zombiesInRadius = (List <Zombie>)zombiesInRadiusField.GetValue(null);
            var animalsInRadius = (List <Animal>)animalsInRadiusField.GetValue(null);

            var targetPlayer = targetPlayerField.GetValue(__instance) as Player;
            var targetZombie = targetZombieField.GetValue(__instance) as Zombie;
            var targetAnimal = targetAnimalField.GetValue(__instance) as Animal;
            var aimTransform = aimTransformField.GetValue(__instance) as Transform;

            if (__instance.isPowered)
            {
                Vector3 vector3_1 = __instance.transform.position + new Vector3(0.0f, 0.65f, 0.0f);
                Vector3 vector3_2;
                if ((double)Time.realtimeSinceStartup - (double)lastScan > 0.100000001490116)
                {
                    lastScanField.SetValue(__instance, Time.realtimeSinceStartup);

                    float a = 48f;
                    if (hasWeapon)
                    {
                        a = Mathf.Min(a, ((ItemWeaponAsset)displayAsset).range);
                    }
                    float  sqrRadius = a * a;
                    float  num       = sqrRadius;
                    Player player    = (Player)null;
                    Zombie zombie    = (Zombie)null;
                    Animal animal    = (Animal)null;
                    if (Provider.isPvP)
                    {
                        playersInRadius.Clear();
                        PlayerTool.getPlayersInRadius(vector3_1, sqrRadius, playersInRadius);
                        for (int index = 0; index < playersInRadius.Count; ++index)
                        {
                            Player playersInRadiu = playersInRadius[index];

                            var currentRocketPlayer = new RocketPlayer(playersInRadiu.channel.owner.playerID.steamID.ToString());

                            if (currentRocketPlayer.HasPermission(GodPermission))
                            {
                                continue;
                            }

                            if (!(playersInRadiu.channel.owner.playerID.steamID == __instance.owner) && !playersInRadiu.quests.isMemberOfGroup(__instance.group) && (!playersInRadiu.life.isDead && playersInRadiu.animator.gesture != EPlayerGesture.ARREST_START) && ((!playersInRadiu.movement.isSafe || !playersInRadiu.movement.isSafeInfo.noWeapons) && playersInRadiu.movement.canAddSimulationResultsToUpdates) && (!((UnityEngine.Object)player != (UnityEngine.Object)null) || playersInRadiu.animator.gesture != EPlayerGesture.SURRENDER_START) && (__instance.sentryMode != ESentryMode.FRIENDLY || (double)Time.realtimeSinceStartup - (double)playersInRadiu.equipment.lastPunching < 2.0 || playersInRadiu.equipment.isSelected && playersInRadiu.equipment.asset != null && playersInRadiu.equipment.asset.shouldFriendlySentryTargetUser))
                            {
                                vector3_2 = playersInRadiu.look.aim.position - vector3_1;
                                float sqrMagnitude = vector3_2.sqrMagnitude;
                                if ((double)sqrMagnitude <= (double)num)
                                {
                                    Vector3 vector3_3 = playersInRadiu.look.aim.position - vector3_1;
                                    float   magnitude = vector3_3.magnitude;
                                    Vector3 vector3_4 = vector3_3 / magnitude;
                                    if (!((UnityEngine.Object)playersInRadiu != (UnityEngine.Object)targetPlayer) || (double)Vector3.Dot(vector3_4, aimTransform.forward) >= 0.5)
                                    {
                                        if ((double)magnitude > 0.025000000372529)
                                        {
                                            RaycastHit hit;
                                            PhysicsUtility.raycast(new Ray(vector3_1, vector3_4), out hit, magnitude - 0.025f, RayMasks.BLOCK_SENTRY, QueryTriggerInteraction.UseGlobal);
                                            if (!((UnityEngine.Object)hit.transform != (UnityEngine.Object)null) || !((UnityEngine.Object)hit.transform != (UnityEngine.Object)__instance.transform))
                                            {
                                                PhysicsUtility.raycast(new Ray(vector3_1 + vector3_4 * (magnitude - 0.025f), -vector3_4), out hit, magnitude - 0.025f, RayMasks.DAMAGE_SERVER, QueryTriggerInteraction.UseGlobal);
                                                if ((UnityEngine.Object)hit.transform != (UnityEngine.Object)null && (UnityEngine.Object)hit.transform != (UnityEngine.Object)__instance.transform)
                                                {
                                                    continue;
                                                }
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }
                                        num    = sqrMagnitude;
                                        player = playersInRadiu;
                                    }
                                }
                            }
                        }
                    }
                    zombiesInRadius.Clear();
                    ZombieManager.getZombiesInRadius(vector3_1, sqrRadius, zombiesInRadius);
                    for (int index = 0; index < zombiesInRadius.Count; ++index)
                    {
                        Zombie zombiesInRadiu = zombiesInRadius[index];
                        if (!zombiesInRadiu.isDead && zombiesInRadiu.isHunting)
                        {
                            Vector3 position = zombiesInRadiu.transform.position;
                            switch (zombiesInRadiu.speciality)
                            {
                            case EZombieSpeciality.NORMAL:
                                position += new Vector3(0.0f, 1.75f, 0.0f);
                                break;

                            case EZombieSpeciality.MEGA:
                                position += new Vector3(0.0f, 2.625f, 0.0f);
                                break;

                            case EZombieSpeciality.CRAWLER:
                                position += new Vector3(0.0f, 0.25f, 0.0f);
                                break;

                            case EZombieSpeciality.SPRINTER:
                                position += new Vector3(0.0f, 1f, 0.0f);
                                break;
                            }
                            vector3_2 = position - vector3_1;
                            float sqrMagnitude = vector3_2.sqrMagnitude;
                            if ((double)sqrMagnitude <= (double)num)
                            {
                                Vector3 vector3_3 = position - vector3_1;
                                float   magnitude = vector3_3.magnitude;
                                Vector3 vector3_4 = vector3_3 / magnitude;
                                if (!((UnityEngine.Object)zombiesInRadiu != (UnityEngine.Object)targetZombie) || (double)Vector3.Dot(vector3_4, aimTransform.forward) >= 0.5)
                                {
                                    if ((double)magnitude > 0.025000000372529)
                                    {
                                        RaycastHit hit;
                                        PhysicsUtility.raycast(new Ray(vector3_1, vector3_4), out hit, magnitude - 0.025f, RayMasks.BLOCK_SENTRY, QueryTriggerInteraction.UseGlobal);
                                        if (!((UnityEngine.Object)hit.transform != (UnityEngine.Object)null) || !((UnityEngine.Object)hit.transform != (UnityEngine.Object)__instance.transform))
                                        {
                                            PhysicsUtility.raycast(new Ray(vector3_1 + vector3_4 * (magnitude - 0.025f), -vector3_4), out hit, magnitude - 0.025f, RayMasks.DAMAGE_SERVER, QueryTriggerInteraction.UseGlobal);
                                            if ((UnityEngine.Object)hit.transform != (UnityEngine.Object)null && (UnityEngine.Object)hit.transform != (UnityEngine.Object)__instance.transform)
                                            {
                                                continue;
                                            }
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    num    = sqrMagnitude;
                                    player = (Player)null;
                                    zombie = zombiesInRadiu;
                                }
                            }
                        }
                    }
                    animalsInRadius.Clear();
                    AnimalManager.getAnimalsInRadius(vector3_1, sqrRadius, animalsInRadius);
                    for (int index = 0; index < animalsInRadius.Count; ++index)
                    {
                        Animal animalsInRadiu = animalsInRadius[index];
                        if (!animalsInRadiu.isDead)
                        {
                            Vector3 position = animalsInRadiu.transform.position;
                            vector3_2 = position - vector3_1;
                            float sqrMagnitude = vector3_2.sqrMagnitude;
                            if ((double)sqrMagnitude <= (double)num)
                            {
                                Vector3 vector3_3 = position - vector3_1;
                                float   magnitude = vector3_3.magnitude;
                                Vector3 vector3_4 = vector3_3 / magnitude;
                                if (!((UnityEngine.Object)animalsInRadiu != (UnityEngine.Object)targetAnimal) || (double)Vector3.Dot(vector3_4, aimTransform.forward) >= 0.5)
                                {
                                    if ((double)magnitude > 0.025000000372529)
                                    {
                                        RaycastHit hit;
                                        PhysicsUtility.raycast(new Ray(vector3_1, vector3_4), out hit, magnitude - 0.025f, RayMasks.BLOCK_SENTRY, QueryTriggerInteraction.UseGlobal);
                                        if (!((UnityEngine.Object)hit.transform != (UnityEngine.Object)null) || !((UnityEngine.Object)hit.transform != (UnityEngine.Object)__instance.transform))
                                        {
                                            PhysicsUtility.raycast(new Ray(vector3_1 + vector3_4 * (magnitude - 0.025f), -vector3_4), out hit, magnitude - 0.025f, RayMasks.DAMAGE_SERVER, QueryTriggerInteraction.UseGlobal);
                                            if ((UnityEngine.Object)hit.transform != (UnityEngine.Object)null && (UnityEngine.Object)hit.transform != (UnityEngine.Object)__instance.transform)
                                            {
                                                continue;
                                            }
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    num    = sqrMagnitude;
                                    player = (Player)null;
                                    zombie = (Zombie)null;
                                    animal = animalsInRadiu;
                                }
                            }
                        }
                    }
                    if ((UnityEngine.Object)player != (UnityEngine.Object)targetPlayer || (UnityEngine.Object)zombie != (UnityEngine.Object)targetZombie || (UnityEngine.Object)animal != (UnityEngine.Object)targetAnimal)
                    {
                        targetPlayerField.SetValue(__instance, player);
                        targetZombieField.SetValue(__instance, zombie);
                        targetAnimalField.SetValue(__instance, animal);
                        lastFireField.SetValue(__instance, Time.realtimeSinceStartup + 0.1f);
                    }
                }
                if ((UnityEngine.Object)targetPlayer != (UnityEngine.Object)null)
                {
                    switch (__instance.sentryMode)
                    {
                    case ESentryMode.NEUTRAL:
                    case ESentryMode.FRIENDLY:
                        isFiringField.SetValue(__instance, targetPlayer.animator.gesture != EPlayerGesture.SURRENDER_START);
                        break;

                    case ESentryMode.HOSTILE:
                        isFiringField.SetValue(__instance, true);
                        break;
                    }
                    isAimingField.SetValue(__instance, true);
                }
                else if ((UnityEngine.Object)targetZombie != (UnityEngine.Object)null)
                {
                    isFiringField.SetValue(__instance, true);
                    isAimingField.SetValue(__instance, true);
                }
                else if ((UnityEngine.Object)targetAnimal != (UnityEngine.Object)null)
                {
                    switch (__instance.sentryMode)
                    {
                    case ESentryMode.NEUTRAL:
                    case ESentryMode.FRIENDLY:
                        isFiringField.SetValue(__instance, targetAnimal.isHunting);
                        break;

                    case ESentryMode.HOSTILE:
                        isFiringField.SetValue(__instance, true);
                        break;
                    }
                    isAimingField.SetValue(__instance, true);
                }
                else
                {
                    isFiringField.SetValue(__instance, false);
                    isAimingField.SetValue(__instance, false);
                }
                if (isAiming && (double)Time.realtimeSinceStartup - (double)lastAim > (double)Provider.UPDATE_TIME)
                {
                    lastAimField.SetValue(__instance, Time.realtimeSinceStartup);
                    Transform transform = (Transform)null;
                    Vector3   vector3_3 = Vector3.zero;
                    if ((UnityEngine.Object)targetPlayer != (UnityEngine.Object)null)
                    {
                        transform = targetPlayer.transform;
                        vector3_3 = targetPlayer.look.aim.position;
                    }
                    else if ((UnityEngine.Object)targetZombie != (UnityEngine.Object)null)
                    {
                        transform = targetZombie.transform;
                        vector3_3 = targetZombie.transform.position;
                        switch (targetZombie.speciality)
                        {
                        case EZombieSpeciality.NORMAL:
                            vector3_3 += new Vector3(0.0f, 1.75f, 0.0f);
                            break;

                        case EZombieSpeciality.MEGA:
                            vector3_3 += new Vector3(0.0f, 2.625f, 0.0f);
                            break;

                        case EZombieSpeciality.CRAWLER:
                            vector3_3 += new Vector3(0.0f, 0.25f, 0.0f);
                            break;

                        case EZombieSpeciality.SPRINTER:
                            vector3_3 += new Vector3(0.0f, 1f, 0.0f);
                            break;
                        }
                    }
                    else if ((UnityEngine.Object)targetAnimal != (UnityEngine.Object)null)
                    {
                        transform = targetAnimal.transform;
                        vector3_3 = targetAnimal.transform.position + Vector3.up;
                    }
                    if ((UnityEngine.Object)transform != (UnityEngine.Object)null)
                    {
                        float  yaw = Mathf.Atan2(vector3_3.x - vector3_1.x, vector3_3.z - vector3_1.z) * 57.29578f;
                        double num = (double)vector3_3.y - (double)vector3_1.y;
                        vector3_2 = vector3_3 - vector3_1;
                        double magnitude = (double)vector3_2.magnitude;
                        float  pitch     = Mathf.Sin((float)(num / magnitude)) * 57.29578f;
                        BarricadeManager.sendAlertSentry(__instance.transform, yaw, pitch);
                    }
                }
                if (isFiring && hasWeapon && (__instance.displayItem.state[10] > (byte)0 && !__instance.isOpen) && (double)Time.realtimeSinceStartup - (double)lastFire > (double)fireTime)
                {
                    lastFireField.SetValue(__instance, lastFire + fireTime);
                    if ((double)Time.realtimeSinceStartup - (double)lastFire > (double)fireTime)
                    {
                        lastFire = Time.realtimeSinceStartup;
                    }
                    float num1 = (float)__instance.displayItem.quality / 100f;
                    if (attachments.magazineAsset == null)
                    {
                        return(false);
                    }

                    if (!ownerPlayer.HasPermission(IgnoreAmmoPermission))
                    {
                        Console.WriteLine("Ammo reduction");
                        if ((__instance.sentryAsset.infiniteAmmo ? 1 : (((ItemGunAsset)displayAsset).infiniteAmmo ? 1 : 0)) == 0)
                        {
                            --__instance.displayItem.state[10];
                        }

                        if (!__instance.sentryAsset.infiniteQuality && Provider.modeConfigData.Items.Has_Durability && (__instance.displayItem.quality > (byte)0 && (double)UnityEngine.Random.value < (double)((ItemWeaponAsset)displayAsset).durability))
                        {
                            if ((int)__instance.displayItem.quality > (int)((ItemWeaponAsset)displayAsset).wear)
                            {
                                __instance.displayItem.quality -= ((ItemWeaponAsset)displayAsset).wear;
                            }
                            else
                            {
                                __instance.displayItem.quality = (byte)0;
                            }
                        }
                    }
                    if (attachments.barrelAsset == null || !attachments.barrelAsset.isSilenced || __instance.displayItem.state[16] == (byte)0)
                    {
                        AlertTool.alert(__instance.transform.position, 48f);
                    }

                    float num2 = ((ItemGunAsset)displayAsset).spreadAim * ((double)num1 < 0.5 ? (float)(1.0 + (1.0 - (double)num1 * 2.0)) : 1f);
                    if (attachments.tacticalAsset != null && interact)
                    {
                        num2 *= attachments.tacticalAsset.spread;
                    }
                    if (attachments.gripAsset != null)
                    {
                        num2 *= attachments.gripAsset.spread;
                    }
                    if (attachments.barrelAsset != null)
                    {
                        num2 *= attachments.barrelAsset.spread;
                    }
                    if (attachments.magazineAsset != null)
                    {
                        num2 *= attachments.magazineAsset.spread;
                    }


                    if ((UnityEngine.Object)((ItemGunAsset)displayAsset).projectile == (UnityEngine.Object)null)
                    {
                        BarricadeManager.sendShootSentry(__instance.transform);
                        byte pellets = attachments.magazineAsset.pellets;
                        for (byte index1 = 0; (int)index1 < (int)pellets; ++index1)
                        {
                            EPlayerKill kill      = EPlayerKill.NONE;
                            uint        xp        = 0;
                            float       times     = (float)(1.0 * ((double)num1 < 0.5 ? 0.5 + (double)num1 : 1.0));
                            Transform   transform = (Transform)null;
                            float       num3      = 0.0f;
                            if ((UnityEngine.Object)targetPlayer != (UnityEngine.Object)null)
                            {
                                transform = targetPlayer.transform;
                            }
                            else if ((UnityEngine.Object)targetZombie != (UnityEngine.Object)null)
                            {
                                transform = __instance.transform;
                            }
                            else if ((UnityEngine.Object)targetAnimal != (UnityEngine.Object)null)
                            {
                                transform = targetAnimal.transform;
                            }
                            if ((UnityEngine.Object)transform != (UnityEngine.Object)null)
                            {
                                vector3_2 = transform.position - __instance.transform.position;
                                num3      = vector3_2.magnitude;
                            }
                            float num4 = (1f - num3 / ((ItemWeaponAsset)displayAsset).range) * (1f - ((ItemGunAsset)displayAsset).spreadHip) * 0.75f;
                            if ((UnityEngine.Object)transform == (UnityEngine.Object)null || (double)UnityEngine.Random.value > (double)num4)
                            {
                                Vector3 forward = aimTransform.forward;
                                forward += aimTransform.right * UnityEngine.Random.Range(-((ItemGunAsset)displayAsset).spreadHip, ((ItemGunAsset)displayAsset).spreadHip) * num2;
                                forward += aimTransform.up * UnityEngine.Random.Range(-((ItemGunAsset)displayAsset).spreadHip, ((ItemGunAsset)displayAsset).spreadHip) * num2;
                                forward.Normalize();
                                RaycastInfo raycastInfo = DamageTool.raycast(new Ray(aimTransform.position, forward), ((ItemWeaponAsset)displayAsset).range, RayMasks.DAMAGE_SERVER);
                                if (!((UnityEngine.Object)raycastInfo.transform == (UnityEngine.Object)null))
                                {
                                    DamageTool.impact(raycastInfo.point, raycastInfo.normal, raycastInfo.material, (UnityEngine.Object)raycastInfo.vehicle != (UnityEngine.Object)null || raycastInfo.transform.CompareTag("Barricade") || raycastInfo.transform.CompareTag("Structure") || raycastInfo.transform.CompareTag("Resource"));
                                    if ((UnityEngine.Object)raycastInfo.vehicle != (UnityEngine.Object)null)
                                    {
                                        DamageTool.damage(raycastInfo.vehicle, false, Vector3.zero, false, ((ItemWeaponAsset)displayAsset).vehicleDamage, times, true, out kill, new CSteamID(), EDamageOrigin.Sentry);
                                    }
                                    else if ((UnityEngine.Object)raycastInfo.transform != (UnityEngine.Object)null)
                                    {
                                        if (raycastInfo.transform.CompareTag("Barricade"))
                                        {
                                            ushort result;
                                            if (ushort.TryParse(raycastInfo.transform.name, NumberStyles.Any, (IFormatProvider)CultureInfo.InvariantCulture, out result))
                                            {
                                                ItemBarricadeAsset itemBarricadeAsset = (ItemBarricadeAsset)Assets.find(EAssetType.ITEM, result);
                                                if (itemBarricadeAsset != null && (itemBarricadeAsset.isVulnerable || ((ItemWeaponAsset)displayAsset).isInvulnerable))
                                                {
                                                    DamageTool.damage(raycastInfo.transform, false, ((ItemWeaponAsset)displayAsset).barricadeDamage, times, out kill, new CSteamID(), EDamageOrigin.Sentry);
                                                }
                                            }
                                        }
                                        else if (raycastInfo.transform.CompareTag("Structure"))
                                        {
                                            ushort result;
                                            if (ushort.TryParse(raycastInfo.transform.name, NumberStyles.Any, (IFormatProvider)CultureInfo.InvariantCulture, out result))
                                            {
                                                ItemStructureAsset itemStructureAsset = (ItemStructureAsset)Assets.find(EAssetType.ITEM, result);
                                                if (itemStructureAsset != null && (itemStructureAsset.isVulnerable || ((ItemWeaponAsset)displayAsset).isInvulnerable))
                                                {
                                                    DamageTool.damage(raycastInfo.transform, false, raycastInfo.direction * Mathf.Ceil((float)attachments.magazineAsset.pellets / 2f), ((ItemWeaponAsset)displayAsset).structureDamage, times, out kill, new CSteamID(), EDamageOrigin.Sentry);
                                                }
                                            }
                                        }
                                        else if (raycastInfo.transform.CompareTag("Resource"))
                                        {
                                            byte   x;
                                            byte   y;
                                            ushort index2;
                                            if (ResourceManager.tryGetRegion(raycastInfo.transform, out x, out y, out index2))
                                            {
                                                ResourceSpawnpoint resourceSpawnpoint = ResourceManager.getResourceSpawnpoint(x, y, index2);
                                                if (resourceSpawnpoint != null && !resourceSpawnpoint.isDead && ((ItemWeaponAsset)displayAsset).hasBladeID(resourceSpawnpoint.asset.bladeID))
                                                {
                                                    DamageTool.damage(raycastInfo.transform, raycastInfo.direction * Mathf.Ceil((float)attachments.magazineAsset.pellets / 2f), ((ItemWeaponAsset)displayAsset).resourceDamage, times, 1f, out kill, out xp, new CSteamID(), EDamageOrigin.Sentry);
                                                }
                                            }
                                        }
                                        else if (raycastInfo.section < byte.MaxValue)
                                        {
                                            InteractableObjectRubble componentInParent = raycastInfo.transform.GetComponentInParent <InteractableObjectRubble>();
                                            if ((UnityEngine.Object)componentInParent != (UnityEngine.Object)null && !componentInParent.isSectionDead(raycastInfo.section) && (componentInParent.asset.rubbleIsVulnerable || ((ItemWeaponAsset)displayAsset).isInvulnerable))
                                            {
                                                DamageTool.damage(componentInParent.transform, raycastInfo.direction, raycastInfo.section, ((ItemWeaponAsset)displayAsset).objectDamage, times, out kill, out xp, new CSteamID(), EDamageOrigin.Sentry);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Vector3 point = Vector3.zero;
                                if ((UnityEngine.Object)targetPlayer != (UnityEngine.Object)null)
                                {
                                    point = targetPlayer.look.aim.position;
                                }
                                else if ((UnityEngine.Object)targetZombie != (UnityEngine.Object)null)
                                {
                                    point = targetZombie.transform.position;
                                    switch (targetZombie.speciality)
                                    {
                                    case EZombieSpeciality.NORMAL:
                                        point += new Vector3(0.0f, 1.75f, 0.0f);
                                        break;

                                    case EZombieSpeciality.MEGA:
                                        point += new Vector3(0.0f, 2.625f, 0.0f);
                                        break;

                                    case EZombieSpeciality.CRAWLER:
                                        point += new Vector3(0.0f, 0.25f, 0.0f);
                                        break;

                                    case EZombieSpeciality.SPRINTER:
                                        point += new Vector3(0.0f, 1f, 0.0f);
                                        break;
                                    }
                                }
                                else if ((UnityEngine.Object)targetAnimal != (UnityEngine.Object)null)
                                {
                                    point = targetAnimal.transform.position + Vector3.up;
                                }
                                DamageTool.impact(point, -aimTransform.forward, EPhysicsMaterial.FLESH_DYNAMIC, true);
                                Vector3 direction = aimTransform.forward * Mathf.Ceil((float)attachments.magazineAsset.pellets / 2f);
                                if ((UnityEngine.Object)targetPlayer != (UnityEngine.Object)null)
                                {
                                    DamageTool.damage(targetPlayer, EDeathCause.SENTRY, ELimb.SPINE, __instance.owner, direction, (IDamageMultiplier)((ItemWeaponAsset)displayAsset).playerDamageMultiplier, times, true, out kill, true, ERagdollEffect.NONE);
                                }
                                else if ((UnityEngine.Object)targetZombie != (UnityEngine.Object)null)
                                {
                                    IDamageMultiplier      damageMultiplier = ((ItemWeaponAsset)displayAsset).zombieOrPlayerDamageMultiplier;
                                    DamageZombieParameters parameters       = DamageZombieParameters.make(targetZombie, direction, damageMultiplier, ELimb.SPINE);
                                    parameters.times       = times;
                                    parameters.legacyArmor = true;
                                    parameters.instigator  = (object)__instance;
                                    DamageTool.damageZombie(parameters, out kill, out xp);
                                }
                                else if ((UnityEngine.Object)targetAnimal != (UnityEngine.Object)null)
                                {
                                    IDamageMultiplier      damageMultiplier = ((ItemWeaponAsset)displayAsset).animalOrPlayerDamageMultiplier;
                                    DamageAnimalParameters parameters       = DamageAnimalParameters.make(targetAnimal, direction, damageMultiplier, ELimb.SPINE);
                                    parameters.times      = times;
                                    parameters.instigator = (object)__instance;
                                    DamageTool.damageAnimal(parameters, out kill, out xp);
                                }
                            }
                        }
                    }
                    __instance.rebuildState();
                }
            }
            return(false);
        }
Beispiel #26
0
 /// <summary>
 /// Returns a new Vector3 instance where fore each component Mathf.Ceil is called
 /// </summary>
 public static Vector3 Ceil(this Vector3 source)
 {
     return(new Vector3(Mathf.Ceil(source.x), Mathf.Ceil(source.y), Mathf.Ceil(source.z)));
 }
Beispiel #27
0
    void BuildMesh()
    {
        MeshClear();

        if (meshColliderMesh != null)
        {
            meshColliderMesh.Clear();
        }


        tk2dSpriteDefinition sprite = CurrentSprite;
        Bounds  bounds           = sprite.GetBounds();
        Vector3 actualSpriteSize = new Vector3(bounds.size.x + 2 * sprite.innerPadding, bounds.size.y + 2 * sprite.innerPadding, bounds.size.z);

        // round fill amount - so vertices and uv become rounded
        float curFillAmount  = mFillAmount;
        bool  fillWasRounded = false;

        if (!isRoundShiftDisabled && (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical))
        {
            float curSize = (mFillDirection == FillDirection.Horizontal) ? actualSpriteSize.x : actualSpriteSize.y;

            curFillAmount *= curSize;
            curFillAmount  = (mInvert) ? Mathf.Ceil(curFillAmount) : Mathf.Floor(curFillAmount);
            curFillAmount /= curSize;

            fillWasRounded = true;
        }

        OnFill(ref tempVertices, ref tempUvs, ref tempColors, curFillAmount);

        Vector3 centerCorrection = new Vector3(-bounds.size.x * 0.5f * scale.x - sprite.innerPadding, bounds.size.y * 0.5f * scale.y + sprite.innerPadding) + bounds.center;
        Vector3 totalScale       = actualSpriteSize;

        totalScale.Scale(scale);

        for (int i = 0; i < tempVertices.Length; i++)
        {
            tempVertices[i] = Vector3.Scale(tempVertices[i], totalScale) + centerCorrection;

            if (!isRoundShiftDisabled)
            {
                if (fillWasRounded)
                {
                    tempVertices[i] = RoundVertex(tempVertices[i]);
                }
                else
                {
                    tempVertices[i] = FloorVertex(tempVertices[i]);
                }
            }
        }


        if (rotated ^ (sprite.flipped == tk2dSpriteDefinition.FlipMode.TPackerCW))
        {
            float u0 = 1;
            float v0 = 1;
            float u1 = 0;
            float v1 = 0;

            foreach (Vector2 v in sprite.uvs)
            {
                u0 = u0 > v.x ? v.x : u0;
                v0 = v0 > v.y ? v.y : v0;

                u1 = u1 < v.x ? v.x : u1;
                v1 = v1 < v.y ? v.y : v1;
            }

            float   du    = (u1 - u0);
            float   dv    = (v1 - v0);
            Vector2 zero  = new Vector2(u0, v0);
            Vector2 zero1 = new Vector2(u1, v0);

            for (int i = 0; i < tempUvs.Length; i++)
            {
                Vector2 uvpos = (tempUvs[i] - zero);
                tempUvs[i] = zero1 + new Vector2(-du * uvpos.y / dv, dv * uvpos.x / du);
            }
        }
        else
        if (rotated ^ (sprite.flipped == tk2dSpriteDefinition.FlipMode.Tk2d))
        {
            float u0 = 1;
            float v0 = 1;
            float u1 = 0;
            float v1 = 0;

            foreach (Vector2 v in sprite.uvs)
            {
                u0 = u0 > v.x ? v.x : u0;
                v0 = v0 > v.y ? v.y : v0;

                u1 = u1 < v.x ? v.x : u1;
                v1 = v1 < v.y ? v.y : v1;
            }

            float   du    = (u1 - u0);
            float   dv    = (v1 - v0);
            Vector2 zero  = new Vector2(u0, v0);
            Vector2 zero1 = new Vector2(u0, v0);

            for (int i = 0; i < tempUvs.Length; i++)
            {
                Vector2 uvpos = (tempUvs[i] - zero);
                tempUvs[i] = zero1 + new Vector2(du * uvpos.y / dv, dv * uvpos.x / du);
            }
        }

        int quads = tempVertices.Length / 4;

        tempIndexes = ArrayExtention.EnsureLength(tempIndexes, quads * 6);

        for (int i = 0; i < quads; i++)
        {
            tempIndexes[6 * i + 0] = 4 * i + 0;
            tempIndexes[6 * i + 1] = 4 * i + 1;
            tempIndexes[6 * i + 2] = 4 * i + 2;
            tempIndexes[6 * i + 3] = 4 * i + 2;
            tempIndexes[6 * i + 4] = 4 * i + 3;
            tempIndexes[6 * i + 5] = 4 * i + 0;
        }


        MeshVertices  = tempVertices;
        MeshUV        = tempUvs;
        MeshColors    = tempColors;
        MeshTriangles = tempIndexes;

        if (meshColliderMesh != null)
        {
            meshColliderMesh.vertices  = tempVertices;
            meshColliderMesh.uv        = tempUvs;
            meshColliderMesh.colors    = tempColors;
            meshColliderMesh.triangles = tempIndexes;
        }


        changed = false;
    }
Beispiel #28
0
    void OnGUI()
    {
        GUI.skin.box.normal.textColor  = new Vector4(1, 1, 1, 1);
        GUI.skin.box.padding           = new RectOffset(15, 15, 15, 15);
        GUI.skin.box.fontSize          = scaleGUI(8);
        GUI.skin.box.alignment         = TextAnchor.UpperLeft;
        GUI.skin.box.normal.background = dialogboxbg;
        GUI.skin.button.fontSize       = scaleGUI(8);
        switch (state)
        {
        case "dialog":
        {
            player.canMove = false;
            if (!string.IsNullOrEmpty(_text))
            {
                dialogbox = new Rect(
                    Screen.width / 2 - scaleGUI(95),
                    Screen.height / 2 - scaleGUI(113),
                    scaleGUI(190),
                    scaleGUI(190));
                GUI.Box(dialogbox, _text);
            }
            if (_choices == null)
            {
                if (GUI.Button(new Rect(
                                   Screen.width / 2 - scaleGUI(95),
                                   Screen.height / 2 + scaleGUI(50),
                                   scaleGUI(190),
                                   scaleGUI(30)),
                               "继续"))
                {
                    Dialoguer.ContinueDialogue();
                }
            }
            else
            {
                pressed = false;
                for (int i = _choices.Length - 1; i >= 0; i--)
                {
                    if (GUI.Button(new Rect(
                                       Screen.width / 2 - scaleGUI(95),
                                       Screen.height / 2 + scaleGUI((i - _choices.Length + 2) * 35),
                                       scaleGUI(190),
                                       scaleGUI(30)),
                                   _choices[i]))
                    {
                        Dialoguer.ContinueDialogue(i);
                    }
                }
            }
        }
        break;

        case "dabuguo":
        {
            player.canMove = false;
            GUI.Box(new Rect(
                        Screen.width / 2 - scaleGUI(72),
                        Screen.height / 2 - scaleGUI(120),
                        scaleGUI(144),
                        scaleGUI(220)),
                    infoDabuguo);
            if (GUI.Button(new Rect(
                               Screen.width / 2 - scaleGUI(60),
                               Screen.height / 2 + scaleGUI(45),
                               scaleGUI(120),
                               scaleGUI(35)),
                           "知道了"))
            {
                state          = string.Empty;
                player.canMove = true;
            }
        }
        break;

        case "floorchange":
        {
            if (dialogTime > 0)
            {
                dialogTime -= Time.deltaTime;
                GUI.Box(new Rect(
                            Screen.width / 2 - scaleGUI(72),
                            Screen.height / 2 - scaleGUI(20),
                            scaleGUI(144),
                            scaleGUI(40)),
                        "当前第 " + _GM.CurrentFloor + " 层");
            }
            else
            {
                dialogTime = 0;
                state      = string.Empty;
            }
        }
        break;

        case "tujian":
            if (Input.GetMouseButton(0))
            {
                GameObject mycamera = GameObject.Find("Camera");
                Vector3    position = mycamera.GetComponent <Camera>().ScreenToWorldPoint(Input.mousePosition);
                TileIndex  ti       = _TM._TileSystem.ClosestTileIndexFromWorld(position);
                TileData   tile     = _TM._TileSystem.GetTile(ti);
                if (tile != null && tile.GetUserFlag(3))
                {
                    Guaiwu guaiwu = tile.gameObject.GetComponent <Guaiwu>();
                    string info   = "";
                    if (!tile.GetUserFlag(10))
                    {
                        if (_PA._gongji <= guaiwu.fangyu)
                        {
                            info = "你破不了它的防御。\n";
                        }
                        else
                        {
                            int   shanghai     = _PA._gongji - guaiwu.fangyu;
                            float cishu        = Mathf.Ceil(guaiwu.shengming / shanghai);
                            float zongshanghai = 0;
                            if (guaiwu.gongji > _PA._fangyu)
                            {
                                float shoushang = guaiwu.gongji - _PA._fangyu;
                                zongshanghai = shoushang * cishu;
                            }
                            info = "战胜它你将损失:" + zongshanghai + "生命。\n";
                        }
                    }
                    info += "生命:" + guaiwu.shengming + "  /  ";
                    info += "攻击:" + guaiwu.gongji + "  /  ";
                    info += "防御:" + guaiwu.fangyu + "\n";
                    info += "金币:" + guaiwu.jinbi + "  /  ";
                    info += "经验:" + guaiwu.jingyan;
                    if (position.y > -5)
                    {
                        //显示在下面
                        GUI.Box(new Rect(
                                    Screen.width / 2 - scaleGUI(95),
                                    Screen.height / 2 + scaleGUI(30),
                                    scaleGUI(190),
                                    scaleGUI(50)),
                                info);
                    }
                    else
                    {
                        //显示在上面
                        GUI.Box(new Rect(
                                    Screen.width / 2 - scaleGUI(95),
                                    Screen.height / 2 - scaleGUI(113),
                                    scaleGUI(190),
                                    scaleGUI(50)),
                                info);
                    }
                }
            }
            break;

        case "feixing":
            player.canMove = false;
            for (int i = 1; i < _GM.maxFloor + 1; i++)
            {
                int y = i % 3;
                if (y == 0)
                {
                    y = -1;
                }
                else if (y == 2)
                {
                    y = 0;
                }
                int z = (i - 1) / 3;
                if (GUI.Button(
                        new Rect(Screen.width / 2 - scaleGUI(60 * y + 35),
                                 Screen.height / 2 - scaleGUI(113) + scaleGUI(25 * z),
                                 scaleGUI(50),
                                 scaleGUI(20)),
                        "第 " + i + " 层"))
                {
                    _GM.changeFloor(i);
                    state          = "";
                    player.canMove = true;
                }
            }
            break;
        }
        if (tipTime > 0 && !string.IsNullOrEmpty(tipContent))
        {
            GUI.skin.box.alignment = TextAnchor.MiddleCenter;
            GUI.Box(new Rect(
                        Screen.width / 2 - scaleGUI(95),
                        Screen.height / 2 + scaleGUI(50),
                        scaleGUI(190),
                        scaleGUI(30)),
                    tipContent);
            tipTime -= Time.deltaTime;
        }
        else
        {
            tipTime    = 0;
            tipContent = string.Empty;
        }
        if (string.IsNullOrEmpty(state))
        {
            player.canMove = true;
        }
    }
Beispiel #29
0
 //= 3 + 10 * 1.05^iLvl + iLvl
 public override float GetMaxRoll(int iLvl)
 {
     return(Mathf.Ceil(3 + 10 * Mathf.Pow(1.05f, iLvl) + iLvl));
 }
Beispiel #30
0
        public override void CachePosition()
        {
            // Width

            var inputsWidth  = 0f;
            var outputsWidth = 0f;

            foreach (var input in inputs)
            {
                inputsWidth = Mathf.Max(inputsWidth, input.GetInnerWidth());
            }

            foreach (var output in outputs)
            {
                outputsWidth = Mathf.Max(outputsWidth, output.GetInnerWidth());
            }

            var portsWidth = 0f;

            portsWidth += inputsWidth;
            portsWidth += Styles.spaceBetweenInputsAndOutputs;
            portsWidth += outputsWidth;

            settingsPositions.Clear();

            var settingsWidth = 0f;

            if (showSettings)
            {
                foreach (var setting in settings)
                {
                    var settingWidth = 0f;

                    var settingLabelContent = settingLabelsContents[setting];

                    if (settingLabelContent != null)
                    {
                        settingWidth += Styles.settingLabel.CalcSize(settingLabelContent).x;
                    }

                    settingWidth += setting.Inspector().GetAdaptiveWidth();

                    settingWidth = Mathf.Min(settingWidth, Styles.maxSettingsWidth);

                    settingsPositions.Add(setting, new Rect(0, 0, settingWidth, 0));

                    settingsWidth = Mathf.Max(settingsWidth, settingWidth);
                }
            }

            var headerAddonWidth = 0f;

            if (showHeaderAddon)
            {
                headerAddonWidth = GetHeaderAddonWidth();
            }

            var titleWidth = Styles.title.CalcSize(titleContent).x;

            var headerTextWidth = titleWidth;

            var surtitleWidth = 0f;

            if (showSurtitle)
            {
                surtitleWidth   = Styles.surtitle.CalcSize(surtitleContent).x;
                headerTextWidth = Mathf.Max(headerTextWidth, surtitleWidth);
            }

            var subtitleWidth = 0f;

            if (showSubtitle)
            {
                subtitleWidth   = Styles.subtitle.CalcSize(subtitleContent).x;
                headerTextWidth = Mathf.Max(headerTextWidth, subtitleWidth);
            }

            var iconsWidth = 0f;

            if (showIcons)
            {
                var iconsColumns = Mathf.Ceil((float)description.icons.Length / Styles.iconsPerColumn);
                iconsWidth = iconsColumns * Styles.iconsSize + ((iconsColumns - 1) * Styles.iconsSpacing);
            }

            var headerWidth = Mathf.Max(headerTextWidth + iconsWidth, Mathf.Max(settingsWidth, headerAddonWidth)) + Styles.iconSize + Styles.spaceAfterIcon;

            var innerWidth = Mathf.Max(portsWidth, headerWidth);

            var edgeWidth = InnerToEdgePosition(new Rect(0, 0, innerWidth, 0)).width;

            // Height & Positioning

            var edgeOrigin  = unit.position;
            var edgeX       = edgeOrigin.x;
            var edgeY       = edgeOrigin.y;
            var innerOrigin = EdgeToInnerPosition(new Rect(edgeOrigin, Vector2.zero)).position;
            var innerX      = innerOrigin.x;
            var innerY      = innerOrigin.y;

            iconPosition = new Rect
                           (
                innerX,
                innerY,
                Styles.iconSize,
                Styles.iconSize
                           );

            var headerTextX = iconPosition.xMax + Styles.spaceAfterIcon;

            var y = innerY;

            var headerHeight = 0f;

            var surtitleHeight = 0f;

            if (showSurtitle)
            {
                surtitleHeight = Styles.surtitle.CalcHeight(surtitleContent, headerTextWidth);

                surtitlePosition = new Rect
                                   (
                    headerTextX,
                    y,
                    headerTextWidth,
                    surtitleHeight
                                   );

                headerHeight += surtitleHeight;
                y            += surtitleHeight;

                headerHeight += Styles.spaceAfterSurtitle;
                y            += Styles.spaceAfterSurtitle;
            }

            var titleHeight = 0f;

            if (showTitle)
            {
                titleHeight = Styles.title.CalcHeight(titleContent, headerTextWidth);

                titlePosition = new Rect
                                (
                    headerTextX,
                    y,
                    headerTextWidth,
                    titleHeight
                                );

                headerHeight += titleHeight;
                y            += titleHeight;
            }

            var subtitleHeight = 0f;

            if (showSubtitle)
            {
                headerHeight += Styles.spaceBeforeSubtitle;
                y            += Styles.spaceBeforeSubtitle;

                subtitleHeight = Styles.subtitle.CalcHeight(subtitleContent, headerTextWidth);

                subtitlePosition = new Rect
                                   (
                    headerTextX,
                    y,
                    headerTextWidth,
                    subtitleHeight
                                   );

                headerHeight += subtitleHeight;
                y            += subtitleHeight;
            }

            iconsPositions.Clear();

            if (showIcons)
            {
                var iconRow = 0;
                var iconCol = 0;

                for (int i = 0; i < description.icons.Length; i++)
                {
                    var iconPosition = new Rect
                                       (
                        innerX + innerWidth - ((iconCol + 1) * Styles.iconsSize) - ((iconCol) * Styles.iconsSpacing),
                        innerY + (iconRow * (Styles.iconsSize + Styles.iconsSpacing)),
                        Styles.iconsSize,
                        Styles.iconsSize
                                       );

                    iconsPositions.Add(iconPosition);

                    iconRow++;

                    if (iconRow % Styles.iconsPerColumn == 0)
                    {
                        iconCol++;
                        iconRow = 0;
                    }
                }
            }

            var settingsHeight = 0f;

            if (showSettings)
            {
                headerHeight += Styles.spaceBeforeSettings;

                foreach (var setting in settings)
                {
                    var settingWidth = settingsPositions[setting].width;

                    using (LudiqGUIUtility.currentInspectorWidth.Override(settingWidth))
                    {
                        var settingHeight = LudiqGUI.GetInspectorHeight(null, setting, settingWidth, settingLabelsContents[setting] ?? GUIContent.none);

                        var settingPosition = new Rect
                                              (
                            headerTextX,
                            y,
                            settingWidth,
                            settingHeight
                                              );

                        settingsPositions[setting] = settingPosition;

                        settingsHeight += settingHeight;
                        y += settingHeight;

                        settingsHeight += Styles.spaceBetweenSettings;
                        y += Styles.spaceBetweenSettings;
                    }
                }

                settingsHeight -= Styles.spaceBetweenSettings;
                y -= Styles.spaceBetweenSettings;

                headerHeight += settingsHeight;

                headerHeight += Styles.spaceAfterSettings;
                y            += Styles.spaceAfterSettings;
            }

            if (showHeaderAddon)
            {
                var headerAddonHeight = GetHeaderAddonHeight(headerAddonWidth);

                headerAddonPosition = new Rect
                                      (
                    headerTextX,
                    y,
                    headerAddonWidth,
                    headerAddonHeight
                                      );

                headerHeight += headerAddonHeight;
                y            += headerAddonHeight;
            }

            if (headerHeight < Styles.iconSize)
            {
                var difference      = Styles.iconSize - headerHeight;
                var centeringOffset = difference / 2;

                if (showTitle)
                {
                    var _titlePosition = titlePosition;
                    _titlePosition.y += centeringOffset;
                    titlePosition     = _titlePosition;
                }

                if (showSubtitle)
                {
                    var _subtitlePosition = subtitlePosition;
                    _subtitlePosition.y += centeringOffset;
                    subtitlePosition     = _subtitlePosition;
                }

                if (showSettings)
                {
                    foreach (var setting in settings)
                    {
                        var _settingPosition = settingsPositions[setting];
                        _settingPosition.y        += centeringOffset;
                        settingsPositions[setting] = _settingPosition;
                    }
                }

                if (showHeaderAddon)
                {
                    var _headerAddonPosition = headerAddonPosition;
                    _headerAddonPosition.y += centeringOffset;
                    headerAddonPosition     = _headerAddonPosition;
                }

                headerHeight = Styles.iconSize;
            }

            y = innerY + headerHeight;

            var innerHeight = 0f;

            innerHeight += headerHeight;

            if (showPorts)
            {
                innerHeight += Styles.spaceBeforePorts;
                y           += Styles.spaceBeforePorts;

                var portsBackgroundY      = y;
                var portsBackgroundHeight = 0f;

                portsBackgroundHeight += Styles.portsBackground.padding.top;
                innerHeight           += Styles.portsBackground.padding.top;
                y += Styles.portsBackground.padding.top;

                var portStartY = y;

                var inputsHeight  = 0f;
                var outputsHeight = 0f;

                foreach (var input in inputs)
                {
                    input.y = y;

                    var inputHeight = input.GetHeight();

                    inputsHeight += inputHeight;
                    y            += inputHeight;

                    inputsHeight += Styles.spaceBetweenPorts;
                    y            += Styles.spaceBetweenPorts;
                }

                if (inputs.Count > 0)
                {
                    inputsHeight -= Styles.spaceBetweenPorts;
                    y            -= Styles.spaceBetweenPorts;
                }

                y = portStartY;

                foreach (var output in outputs)
                {
                    output.y = y;

                    var outputHeight = output.GetHeight();

                    outputsHeight += outputHeight;
                    y             += outputHeight;

                    outputsHeight += Styles.spaceBetweenPorts;
                    y             += Styles.spaceBetweenPorts;
                }

                if (outputs.Count > 0)
                {
                    outputsHeight -= Styles.spaceBetweenPorts;
                    y             -= Styles.spaceBetweenPorts;
                }

                var portsHeight = Math.Max(inputsHeight, outputsHeight);

                portsBackgroundHeight += portsHeight;
                innerHeight           += portsHeight;
                y = portStartY + portsHeight;

                portsBackgroundHeight += Styles.portsBackground.padding.bottom;
                innerHeight           += Styles.portsBackground.padding.bottom;
                y += Styles.portsBackground.padding.bottom;

                portsBackgroundPosition = new Rect
                                          (
                    edgeX,
                    portsBackgroundY,
                    edgeWidth,
                    portsBackgroundHeight
                                          );
            }

            var edgeHeight = InnerToEdgePosition(new Rect(0, 0, 0, innerHeight)).height;

            _position = new Rect
                        (
                edgeX,
                edgeY,
                edgeWidth,
                edgeHeight
                        );
        }