Scan() public method

public Scan ( ) : void
return void
Ejemplo n.º 1
0
    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Pathing")
        {
            Debug.Log("CHOOSING on transform " + Array.IndexOf(setPath, collision.transform).ToString());
            pathNumber = ChooseClosestDestination(Array.IndexOf(setPath, collision.transform) + setPath.Length);
            Debug.Log("The path number is " + pathNumber.ToString());

            /*Debug.Log("The next target is " + pathNumber.ToString());
             * ghost.Rotate(new Vector3(0, 0, -MathFormula.DotProductAngle(MathFormula.Vector3Converter(ghost.position), MathFormula.Vector3Converter(ghostEye.position), MathFormula.Vector3Converter(setPath[pathNumber % setPath.Length].position))));*/
            if (followPath && destinationNow.name == collision.name)
            {
                destination.target = setPath[pathNumber % setPath.Length];
                destinationNow     = setPath[pathNumber % setPath.Length];
                graph.Scan(); // need to find a delegate/event to call this instead
            }
        }

        if (collision.gameObject.tag == "Item")
        {
            //shouldnt die but yes
            gameObject.SetActive(false);
        }
    }
Ejemplo n.º 2
0
    void Respawn(Transform positionBody, Transform rotationBody)
    {
        level.Initialize();
        path.Scan();
        player.AddElementStack(this.exit);
        Transform parent = this.start.parent.parent;

        float   angle = 90f + parent.eulerAngles.z;
        Vector3 pos   = -Vector3.up;

        switch (angle)
        {
        case 180f: pos = -Vector3.up; break;

        case 0f: pos = Vector3.up; break;

        case -90f: pos = -Vector3.right; break;

        case 90f: pos = Vector3.right; break;
        }

        rotationBody.rotation = Quaternion.Euler(0f, 0f, angle);
        positionBody.position = this.start.position + pos;
    }
Ejemplo n.º 3
0
        /// <summary>
        /// scan map for target if current target is a waypoint
        /// </summary>
        public void TryMapScanning()
        {
            if (GameManager.GetInstance().CurrentSection == null)
            {
                return;
            }

            if (_gridGraph == null)
            {
                StartCoroutine(TryRescan());
            }
            else
            {
                Debug.Log("[GraphBuilder.cs] Rescan graph");

                Section section = GameManager.GetInstance().CurrentSection;

                _gridGraph.nodeSize      = 0.25f;
                _gridGraph.center        = section.transform.position - (Vector3.up * 15);
                _gridGraph.unclampedSize = new Vector2(section.TerrainSize.x * 1.8f, section.TerrainSize.z);

                _path.Scan();
            }
        }
Ejemplo n.º 4
0
    // Check if player enters the room
    void OnTriggerEnter2D(Collider2D other)
    {
        // Entering another trigger causes this to trigger again
        // Need a check to see when the player is in this room and when they leave
        if (other.gameObject.GetComponent <PlayerCharacter>() != null)
        {
            other.gameObject.GetComponent <PlayerCharacter>().currentRoom = this;
            GameObject  roomParts  = this.transform.Find("Room Bits").gameObject; //.layer = 9;
            Transform[] childParts = roomParts.GetComponentsInChildren <Transform>();

            foreach (Transform child in childParts)
            {
                child.gameObject.layer = 9;
            }


            if (isOccupied == true || other.gameObject.GetComponent <PlayerCharacter>().respawning == true)
            {
                return;
            }
            else
            {
                isOccupied = true;
            }
        }

        RoomMoving tempPlay = other.GetComponent <RoomMoving>();

        if (tempPlay == null)
        {
            return;
        }
        else if (tempPlay.curRoom == null)
        {
            tempPlay.curRoom = this;
            return;
        }

        Room oldRoom = tempPlay.curRoom;

        other.gameObject.GetComponent <PlayerCharacter>().lastRoom = oldRoom;

        tempPlay.transform.parent = tempPlay.curRoom.transform;
        Vector2 offset = other.transform.localPosition;

        tempPlay.transform.parent = null;

        if (Mathf.Abs(offset.x) > Mathf.Abs(offset.y))
        {
            offset.x *= -0.75f;
        }
        else
        {
            // if needed because check is done on player body centre, so feet location are different
            if (offset.y > 0)
            {
                offset.y *= -0.55f;
            }
            else
            {
                offset.y *= -0.75f;
            }
        }

        tempPlay.curRoom                 = this;
        tempPlay.transform.parent        = this.transform;
        tempPlay.transform.localPosition = offset;
        tempPlay.transform.parent        = null;

        // Tell the old room the player is no longer in it so it can be entered properly again
        other.gameObject.GetComponent <PlayerCharacter>().lastRoom.isOccupied = false;

        if (other.tag == "Player")
        {
            if (other.GetComponent <PlayerCharacter>().moly == true)
            {
                other.GetComponent <PlayerCharacter>().molyBuff = true;
            }

            Camera.main.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, -10);

            // If the room hasn't been entered before, we need to fill it
            if (isPopulated == false)
            {
                // Activate spawners if any
                if (spawners != null)
                {
                    foreach (Transform child in spawners.transform)
                    {
                        child.GetComponent <Spawner>().Spawn(this.gameObject);
                    }
                }

                isPopulated = true;
            }
            else if (isPopulated == true && diedHere == true && isClear == false)
            {
                diedHere = false;

                // Respawn any enemies and bosses
                if (spawners != null)
                {
                    foreach (Transform child in spawners.transform)
                    {
                        if (child.tag == "EnemySpawn" || child.tag == "BossSpawn")
                        {
                            child.GetComponent <Spawner>().Spawn(this.gameObject);
                        }
                    }
                }
            }

            // Recalculate grid to new room position
            AstarPath obj = FindObjectOfType <AstarPath>();
            obj.data.gridGraph.center = this.transform.position;
            obj.Scan();
        }
    }
Ejemplo n.º 5
0
 // Use this for initialization
 void Start()
 {
     aStarController.Scan();
 }
Ejemplo n.º 6
0
    private void SetUpPathFinding()
    {
        //pfGo = GameObject.Find("PathFinding");
        pf = this.GetComponent<AstarPath>();
        //set path finding region to the center of building
        Vector3 center = HoUtility.GetCenterOfGroup(mainObject);
        Debug.Log ("Center point: " + center);
        pf.transform.position = new Vector3(center.x,0F,center.z);
        ground.transform.position = new Vector3(center.x,-0.1F,center.z);
        //begin scanning
        pf.Scan ();

        cusSeeker.Rescan = true;
    }
    // Start is called before the first frame update
    private void Start()
    {
        //스트레스 테스트 기능은 맵이 만들어지고 스캔이 끝난 후 가능하므로 꺼둔다.
        StressTestButton.gameObject.SetActive(false);

        MazeGenerator mazeGenerator = new MazeGenerator();
        var           mapData       = mazeGenerator.FromDimensions(MapWidth, MapHeight);

        for (int x = 0; x < mapData.GetLength(0); x++)
        {
            for (int z = 0; z < mapData.GetLength(1); z++)
            {
                if (mapData[x, z] == 1)
                {
                    var newWall = Instantiate(WallPrf, new Vector3(x + this.transform.position.x, 0, z + this.transform.position.z) * BlockScale, Quaternion.identity);
                    newWall.transform.SetParent(WallParent.transform);
                    newWall.transform.localScale = new Vector3(1, 4f, 1) * BlockScale;
                    //큰 맵에서 부하를 줄이기 위해 그리기를 꺼준다.
                    newWall.GetComponent <MeshRenderer>().enabled = false;
                }
            }
        }

        // 블럭들을 하나의 메시로 합친다. (그려주기 부담을 줄이자) -> 정점을 합치지 않아서 의미가 없었다. 대신 텍스쳐 한장을 그려서 덮는걸로 변경.
        //MeshMerger.Merge();

        //지형을 텍스쳐로 그려준다.
        WallPlane.transform.position = new Vector3(MapWidth / 2 - BlockScale / 2f, 0.5f, MapHeight / 2 - BlockScale / 2f);
        WallPlane.transform.Rotate(Vector3.up, 180);
        WallPlane.transform.localScale = new Vector3(MapWidth / 10, 1, MapHeight / 10);
        WallPlane.GetComponent <MeshRenderer>().material.mainTexture = WallTextureCreate(mapData);

        //빈방들을 체크해둔다.
        OpenSpaces = GetOpenSpaces(mapData);

        //변경된 미로에 따라 길을 생성한다.
        //bug : 어째서인지, 벽들이 다 생성되기 전에 스캔을 하는 것 같다...
        var gridGraph = AstarPath.graphs.First() as GridGraph;

        gridGraph.SetDimensions(MapWidth, MapHeight, BlockScale);
        gridGraph.center = new Vector3(MapWidth / 2 + BlockScale / 2f, 0, MapHeight / 2 + BlockScale / 2f);

        AstarPath.active.data.recastGraph.forcedBoundsCenter = new Vector3(MapWidth / 2 + BlockScale / 2f, 0, MapHeight / 2 + BlockScale / 2f);
        AstarPath.active.data.recastGraph.forcedBoundsSize   = new Vector3(MapWidth, 1, MapHeight);

        AstarPath.Scan();

        //봇들을 미로에 따라 생성한다.
        //BotGenerator.GenerateBots(mapData);

        //스트레스 테스트를 할 수 있게 버튼을 켠다.
        StressTestButton.gameObject.SetActive(true);
        StressTestButton.onClick.AddListener(StressTest);

        //카메라 조정.
        var cam = Camera.main;

        cam.orthographicSize   = Mathf.Max(MapWidth, MapHeight) / 2;
        cam.transform.position = new Vector3(MapWidth / 2, 400, MapHeight / 2); //xz 축임에 주의.

        //hack : 위 문제 때문에 강제로 스캔하게 한다.
        ForceScanButton.onClick.AddListener(() => AstarPath.Scan());
        SpawnSimpleBotButton.onClick.AddListener(() => SpawnSimpleBots(SimpleBotSpawnAmount, OpenSpaces));
        SpawnNotSimpleBotButton.onClick.AddListener(() => BotGenerator.GenerateBots(mapData, NotSimpleBotSpawnAmount));
    }
Ejemplo n.º 8
0
 public void RecalcWholeNavMesh()
 {
     astarPath.Scan();
 }
Ejemplo n.º 9
0
    // Update is called once per frame
    void Update()
    {
        ///

        ///
        if (isBuildPanel && !upgradePanelOpen)
        {
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 1000, placementLayer))
            {
                if (lastHitObj)
                {
                    lastHitObj.renderer.material = originalMat;
                }

                lastHitObj  = hit.collider.gameObject;
                originalMat = lastHitObj.renderer.material;
                lastHitObj.renderer.material = hoverMat;
            }
            else
            {
                if (lastHitObj)
                {
                    lastHitObj.renderer.material = originalMat;
                    lastHitObj = null;
                }
            }
            if (Input.GetMouseButtonDown(0) && lastHitObj)
            {
                focusedPlain = (PlacementPlain)lastHitObj.GetComponent("PlacementPlain");
                //Debug.Log("Click!");

                if (lastHitObj.tag == "Placement_Open" && levelMaster.WeaponPrices[structureIndex] <= levelMaster.cashCount &&
                    levelMaster.WeaponAvailibility[structureIndex] <= levelMaster.waveLevel)
                {
                    //Debug.Log("Placement Open");
                    Vector3 vec3;

                    // fixing pivot point mistake
                    if (structureIndex == 1)
                    {
                        vec3 = new Vector3(lastHitObj.transform.position.x, lastHitObj.transform.position.y + 0.30f, lastHitObj.transform.position.z);                      //if launcher move little bit up
                    }
                    else
                    {
                        vec3 = new Vector3(lastHitObj.transform.position.x, lastHitObj.transform.position.y, lastHitObj.transform.position.z);
                    }



                    GameObject newStructure = (GameObject)Instantiate(allStructures[structureIndex], lastHitObj.transform.position, Quaternion.identity);
                    newStructure.transform.position = vec3;

                    newStructure.transform.localEulerAngles = new Vector3(newStructure.transform.localEulerAngles.x, Random.Range(0, 360), newStructure.transform.localEulerAngles.z);
                    newStructure.tag = "Obstacles";
                    //newStructure.layer = 10;
                    lastHitObj.tag           = "Placement_Taken";
                    focusedPlain.myStructure = newStructure;

                    levelMaster.cashCount -= levelMaster.WeaponPrices[structureIndex];
                    levelMaster.HUDUpdate();


                    astar.Scan();
                    Debug.Log("Scan");
                    foreach (GameObject tnk in GameObject.FindGameObjectsWithTag("Ground Enemy"))
                    {
                        Tank tnkScript = (Tank)tnk.GetComponent("Tank");
                        tnkScript.FindNewPath();
                    }
                    //UpdateGUI();
                }
/*UPGRADE*/ else if (lastHitObj.tag != "Placement_Open")
                {
                    //upgrade turret

                    turretToUpgrade = (BaseTurret)focusedPlain.myStructure.GetComponent("BaseTurret");
                    if (turretToUpgrade.updateObject)
                    {
                        upgradeCost      = turretToUpgrade.updateCost;
                        upgradeText.text = "Upgrade to\n " + turretToUpgrade.name + " $" + turretToUpgrade.updateCost + "?";
                        CheckUpgradeAvailible();
                        upgradePanelTweener.enabled = true;
                        upgradePanelTweener.Play(true);
                        upgradePanelOpen = true;
                    }

                    //Debug.Log ("upgrade panel");
                }
            }
        }         //isBuildPanel
    }
Ejemplo n.º 10
0
    // Update is called once per frame
    void Update()
    {
        //---GUI
        if (livesCount <= 0)
        {
            GameOverPanel();
            return;
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            ToggleSettingsPanel();
        }
        if (buildPanelOpen)
        {
            var        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 1000, placementLayerMask))
            {
                if (lastHitObj)
                {
                    (lastHitObj.GetComponent <MeshRenderer>()).material = originalMat;
                }

                lastHitObj  = hit.collider.gameObject;
                originalMat = (lastHitObj.GetComponent <MeshRenderer>()).material;
                (lastHitObj.GetComponent <MeshRenderer>()).material = hoverMat;
            }
            else
            {
                if (lastHitObj)
                {
                    (lastHitObj.GetComponent <MeshRenderer>()).material = originalMat;
                    lastHitObj = null;
                }
            }

            //drop turrets on click
            if (Input.GetMouseButtonDown(0) && lastHitObj && // 0 - left button
                !upgradePanelOpen && !GameController.IsPause)
            {
                focusedPlane = lastHitObj.GetComponent <PlacementPlane>();
                int turretCost = allStructures[structureIndex].myCost;
                if (focusedPlane.isOpen && turretCost <= cashCount)
                {
                    GameObject newStructure = Instantiate(allStructures[structureIndex].gameObject,
                                                          lastHitObj.transform.position,
                                                          Quaternion.identity) as GameObject;

                    newStructure.transform.localEulerAngles = new Vector3(
                        newStructure.transform.localEulerAngles.x,
                        Random.Range(0, 360),
                        newStructure.transform.localEulerAngles.z);

                    focusedPlane.myStructure = newStructure;
                    focusedPlane.isOpen      = false;

                    UpgradeCash(-turretCost);

                    //update the Graph
                    // rebuild the Graph
                    AstarController.Scan();

                    foreach (GameObject theEnemy in
                             GameObject.FindGameObjectsWithTag("Ground Enemy"))
                    {
                        theEnemy.GetComponent <AI_Pather>().GetNewPath();
                    }
                }
                else if (focusedPlane.myStructure != null)
                {
                    ShowUpgradeGUI();
                }
            }
        }
        //---End GUI

        //wave
        if (waveActive)
        {
            if (Time.time >= waveEndTime)
            {
                //stop spawn enemies
                spawnEnemies = false;

                if (enemyCount == 0)
                {
                    // Корутин
                    StartCoroutine(FinishWave());
                }
            }
            if (spawnEnemies)
            {
                // if wave still going, spawn enemies
                if (Time.time > (lastSpawnTime + respawnInterval))
                {
                    SpawnNewEnemy();
                }
            }
        }
    }
Ejemplo n.º 11
0
 void Scan()
 {
     path.Scan();
 }
Ejemplo n.º 12
0
 void Start()
 {
     PathComponent.data.gridGraph.nodeSize = ((TileStorageComponent.Width + TileStorageComponent.Height) / 2) / TileStorageComponent.PixelsPerUnit;
     PathComponent.Scan();
 }
Ejemplo n.º 13
0
 public void GrabObject()
 {
     if (d.tag.Equals("Enemy"))
     {
         if (grabber.IsTouching(d.GetComponent <CapsuleCollider2D>()))
         {
             if (grabObj && d.draggable && canGrab)
             {
                 d.GetComponent <EnemyAI>().useDefaultMovement = false;
                 //we set it as a child of the stem
                 d.transform.SetParent(this.transform.parent);
                 d.transform.position = this.transform.position;
                 d.transform.rotation = Quaternion.identity;
                 d.IsHeld             = true;
                 hldObj   = true;
                 canShoot = false;
                 canGrab  = false;
                 path.Scan();
                 grabObj   = false;
                 timeDelay = 0;
             }
         }
     }
     else if (d.tag.Equals("Obstacle"))
     {
         if (grabber.IsTouching(d.GetComponent <BoxCollider2D>()))
         {
             if (grabObj && d.draggable && canGrab)
             {
                 //we set it as a child of the stem
                 d.transform.SetParent(this.transform.parent);
                 d.transform.position = this.transform.position;
                 Debug.Log(d.transform.name + " is Grabbed");
                 d.gameObject.layer   = 0;
                 d.transform.rotation = this.transform.rotation;
                 d.IsHeld             = true;
                 originalDurability   = d.durability;
                 hldObj   = true;
                 canShoot = false;
                 canGrab  = false;
                 path.Scan();
                 grabObj   = false;
                 timeDelay = 0;
             }
         }
     }
     // make sure we grab correct obj
     if (hldObj && d.transform.parent != this.transform.parent)
     {
         d = this.transform.parent.GetComponentInChildren <Draggable>();
     }
     //check if enemy was destroyed while grabbed
     if (d.tag.Equals("Enemy") && hldObj)
     {
         if (d.GetComponent <EnemyAI>().Health <= 0)
         {
             d        = null;
             hldObj   = false;
             canShoot = true;
             StartCoroutine(canActAgain(waitTime));
         }
     }
     // check if the object is destroyed while being held special of Obstacles
     if (d.tag.Equals("Obstacle") && hldObj)
     {
         if (d.durability < originalDurability)
         {
             originalDurability = d.durability;
             grip -= maxGrip / 4f;
         }
         if (d.durability <= 0)
         {
             d        = null;
             hldObj   = false;
             canShoot = true;
             StartCoroutine(canActAgain(waitTime));
         }
     }
     //to keep the object at the grabbers location
     if (hldObj && d.transform.localPosition != transform.localPosition + addDirection)
     {
         d.transform.localPosition = transform.localPosition + addDirection;
     }
     //drop gripTimer if grabbing enemy
     if (hldObj && d.tag.Equals("Enemy"))
     {
         grip -= Time.deltaTime;
     }
 }
Ejemplo n.º 14
0
    private void Start()
    {
        player = FindObjectOfType <PlayerController>();
        gm     = GameManager.instanceGM;
        //for (int i = 0; i < doors.Length; i++)
        //    if (doors[i] != null)
        //        doors[i].SetActive(false);
        //
        //int doorToOpen = Random.Range(0, doors.Length);
        //if (doors[doorToOpen] != null)
        //    doors[doorToOpen].SetActive(true);
        //

        for (int i = 0; i < levels.Length; i++)
        {
            if (levels[i] != null)
            {
                levels[i].SetActive(false);
            }
        }

        if (levels[actualLevel] != null)
        {
            levels[actualLevel].SetActive(true);
        }

        paths.Scan();

        for (int i = 0; i < doorsLvl1.Count; i++)
        {
            if (doorsLvl1[i] != null)
            {
                doorsLvl1[i].SetActive(false);
            }
        }
        for (int i = 0; i < doorsLvl2.Count; i++)
        {
            if (doorsLvl2[i] != null)
            {
                doorsLvl2[i].SetActive(false);
            }
        }

        for (int i = 0; i < doorsLvl3.Count; i++)
        {
            if (doorsLvl3[i] != null)
            {
                doorsLvl3[i].SetActive(false);
            }
        }


        if (actualLevel == 1)
        {
            player.transform.position = doorsLvl1[UnityEngine.Random.Range(0, doorsLvl1.Count)].transform.position;
        }
        else if (actualLevel == 2)
        {
            player.transform.position = doorsLvl2[UnityEngine.Random.Range(0, doorsLvl2.Count)].transform.position;
        }
        else if (actualLevel == 3)
        {
            player.transform.position = doorsLvl3[UnityEngine.Random.Range(0, doorsLvl3.Count)].transform.position;
        }
    }
Ejemplo n.º 15
0
    // Initiate, resize and Scan the pathfind GridGraph
    public void IniPathfindGraph(int _sizeX, int _sizeZ)
    {
        _Astar = GameObject.FindGameObjectWithTag ("Astar").GetComponent<AstarPath>();

        GridGraph _Graph = AstarPath.active.astarData.gridGraph;

        _Graph.width = _sizeX;
        _Graph.depth = _sizeZ;
        _Graph.center = new Vector3(_sizeX/2, 0.0f, _sizeZ/2);
        _Graph.UpdateSizeFromWidthDepth();
        _Graph.Scan();
        _Astar.Scan ();
        AstarPath.active.Scan ();
    }
Ejemplo n.º 16
0
    public void initMap()
    {
        //关卡阶段
        level = GameManager.Instance.sceneLevel / 5;
        if (GameManager.Instance.sceneLevel == 5)
        {
            AudioManager.Instance.StopPlayBGM();
        }
        //创建地板和围墙
        if (mapholder != null)
        {
            Destroy(mapholder.gameObject);
            mapholder = null;
        }
        mapholder = new GameObject("Map").transform;
        for (int i = 0; i < xLength; i++)
        {
            for (int j = 0; j < yLength; j++)
            {
                if (i == 0 || j == 0 || i == xLength - 1 || j == yLength - 1)
                {
                    GameObject go = GameObject.Instantiate(wall[1], new Vector3(i, j, 0), Quaternion.identity);
                    go.transform.SetParent(mapholder);
                }
                else
                {
                    GameObject go = GameObject.Instantiate(floor, new Vector3(i, j, 0), Quaternion.identity);
                    go.transform.SetParent(mapholder);
                }
            }
        }

        positionList.Clear();
        for (int x = 1; x < xLength - 1; x++)
        {
            for (int y = 1; y < yLength - 1; y++)
            {
                positionList.Add(new Vector2(x, y));
            }
        }

        for (int x = 1; x < 4; x++)
        {
            for (int y = 1; y < 4; y++)
            {
                positionList.Remove(new Vector2(x, y));
            }
        }

        //创建主角
        if (GameManager.Instance.isFirstStart)
        {
            GameManager.Instance.isFirstStart = false;
            GameObject p = GameObject.Instantiate(player, new Vector2(1, 1), Quaternion.identity);
            GameManager.Instance.player = p;
            //   p.transform.SetParent(mapholder);
            // player.GetComponent<playInfo>().RoleType = (RoleType)PlayerPrefs.GetInt("roleType", 0);
        }


        //创建围墙

        SpawnWall(new Vector2(Random.Range(xLength / 5, xLength / 2), 0), 0);
        SpawnWall(new Vector2(Random.Range(xLength / 5, xLength / 2), yLength - 1), 0);
        SpawnWall(new Vector2(0, Random.Range(yLength / 5, yLength / 2)), 0);
        SpawnWall(new Vector2(xLength - 1, Random.Range(yLength / 5, yLength / 2)), 0);
        SpawnWall(new Vector2(Random.Range(xLength / 2, xLength - 1), yLength - 1), 0);
        SpawnWall(new Vector2(Random.Range(xLength / 2, xLength - 1), 0), 0);



        //创建障碍物
        int barrierCount = Random.Range(minBarrierCount, maxBarrierCount + 1);

        for (int i = 0; i < barrierCount; i++)
        {
            CreateItemWithoutDoor(barrier, minBarrierCount, maxBarrierCount);
        }
        //创建宝箱
        int chestCount = Random.Range(minChestCount, maxChestCount + 1);

        for (int i = 0; i < chestCount; i++)
        {
            CreateItemWithoutDoor(medicalChest, minChestCount, maxChestCount);
        }

        //创建传送门
        Vector2    portalPos = new Vector2(xLength - 2, yLength - 2);
        GameObject port      = GameObject.Instantiate(portal, portalPos, Quaternion.identity);

        port.transform.SetParent(mapholder);
        positionList.Remove(portalPos);


        //创建医疗机器人
        if (GameManager.Instance.sceneLevel % 5 == 3)
        {
            CreateItemWithoutDoor(medicalRobot, 1, 2);
        }

        //创建敌人
        int enemyCount = Random.Range(minenemyCount, maxenemyCount + 1);

        for (int i = 0; i < enemyCount; i++)
        {
            int enemy_index = Random.Range(0, 2);
            CreateItem(enemy[enemy_index], minenemyCount, maxenemyCount);
        }
        if (GameManager.Instance.sceneLevel % 5 == 1)
        {
            CreateBigItem(enemy[2], 1, 2);
        }
        astarPath = GetComponent <AstarPath>();
        if (astarPath)
        {
            astarPath.Scan();
        }
    }
Ejemplo n.º 17
0
 private void UpdatePath()
 {
     Debug.Log("ScanStart");
     path.Scan();
     Debug.Log("ScanComplete");
 }
Ejemplo n.º 18
0
    void Start()
    {
        // These variables will change their meaning over the course of the method
        RoomControl thisRoom;
        RoomControl adjRoom;
        RoomControl chosenRoom;
        Vector2     roomVector;
        Vector2     roomVectorRel;
        Ramp        r2   = r.GetComponent <Ramp> ();
        double      ramp = Math.Pow(r2.ramp, r2.times);

        // All level components are scaled based on the current required difficulty.
        // Debugging added to aid testing.

        Debug.Log("We r ramp!");

        double temp;

        temp              = (double)roomsToSpawn * ramp;
        roomsToSpawn      = (int)temp;
        temp              = (double)totalEnemies * ramp;
        totalEnemies      = (int)temp;
        temp              = (double)maxEnemiesPerRoom * ramp;
        maxEnemiesPerRoom = (int)temp;

        Debug.Log("Pls make me " + roomsToSpawn.ToString() + " rooms kthanx");
        Debug.Log("Ramp was " + ramp.ToString() + ". Hopefully that's what you expected.");


        // Reference the minimap, so it can be generated in unison with the actual floor
        MinimapScript minimapScript = minimapUI.GetComponent <MinimapScript>();

        // Start room

        thisRoom           = ((GameObject)Instantiate(roomPrefab, new Vector3(0, 0, 0), Quaternion.identity)).GetComponent <RoomControl>();
        thisRoom.minimapUI = minimapUI;
        thisRoom.Floor     = startPrefab;     // pick set floor

        thisRoom.Index = new Vector2(0, 0);
        minimapScript.GenerateMapBlock(thisRoom.Index);

        roomsDict.Add(thisRoom.Index, thisRoom);

        thisRoom.gameObject.name = "Room " + 0;
        thisRoom.spawnEnemies    = false;
        thisRoom.spawnWebs       = false;

        thisRoom.gameObject.transform.Find("Lights").gameObject.SetActive(true);

        // normal rooms

        for (int i = 1; i < roomsToSpawn - 1; i++)
        {
            int a = 0;
            do
            {
                adjRoom = RandomRoom();
                if (a > 1000)
                {
                    throw new System.Exception("Infinite loop occuring.");
                }
                a++;
            } while (!IsNextToEmpty(adjRoom));

            roomVectorRel = RandomEmpty(adjRoom);
            roomVector    = adjRoom.Index + roomVectorRel;

            thisRoom           = ((GameObject)Instantiate(roomPrefab, RoomControl.IndexToPosition(roomVector), Quaternion.identity)).GetComponent <RoomControl>();
            thisRoom.minimapUI = minimapUI;
            thisRoom.Floor     = floorPrefabs[UnityEngine.Random.Range(0, floorPrefabs.Count)];
            thisRoom.Index     = roomVector;
            minimapScript.GenerateMapBlock(thisRoom.Index);
            thisRoom.gameObject.name = "Room " + i;

            SetAdj(adjRoom, roomVectorRel, thisRoom);

            roomsDict.Add(thisRoom.Index, thisRoom);
        }

        // boss room

        int b = 0;

        do
        {
            adjRoom = RandomRoom();
            if (b > 1000)
            {
                throw new System.Exception("Infinite loop occuring.");
            }
            b++;
        } while (!IsNextToEmpty(adjRoom));

        roomVectorRel = RandomEmpty(adjRoom);
        roomVector    = adjRoom.Index + roomVectorRel;

        thisRoom           = ((GameObject)Instantiate(roomPrefab, RoomControl.IndexToPosition(roomVector), Quaternion.identity)).GetComponent <RoomControl>();
        thisRoom.minimapUI = minimapUI;
        thisRoom.Floor     = bossFloor;
        thisRoom.Index     = roomVector;
        minimapScript.GenerateMapBlock(thisRoom.Index);
        thisRoom.gameObject.name = "Boss Room";

        SetAdj(adjRoom, roomVectorRel, thisRoom);

        roomsDict.Add(thisRoom.Index, thisRoom);

        if (boss.transform.name == "Boss3")
        {
            int temp1 = UnityEngine.Random.Range(-18, 18);
            int temp2 = UnityEngine.Random.Range(-10, 10);
            boss = (GameObject)Instantiate(boss, thisRoom.transform.position + new Vector3(temp1, 2, temp2), Quaternion.identity);
            BossThree bs3 = boss.GetComponent <BossThree> ();
            bs3.roomCont = thisRoom.GetComponent <RoomControl> ();
        }
        else if (boss.transform.name == "FlyBoss" || boss.transform.name == "FlyBossTest")
        {
            boss = (GameObject)Instantiate(boss, thisRoom.transform.position + new Vector3(0, 4, 0), Quaternion.identity);
        }
        else
        {
            boss = (GameObject)Instantiate(boss, thisRoom.transform.position + new Vector3(0, 2, 0), Quaternion.identity);
        }

        // Buffs boss health and damage based on ramp params.
        temp = (double)boss.GetComponent <EnemyHealth> ().currentHealth *ramp;
        boss.GetComponent <EnemyHealth> ().currentHealth = (int)temp;
        temp = (double)boss.GetComponent <EnemyHealth> ().startingHealth *ramp;
        boss.GetComponent <EnemyHealth> ().startingHealth = (int)temp;
        temp = (double)boss.GetComponent <EnemyAttack> ().damage *ramp;
        boss.GetComponent <EnemyAttack> ().damage = (int)temp;

        boss.GetComponent <AIPath>().target = GameObject.FindWithTag("Player").transform;


        // link rooms
        // ensures no infinite loops by incrementing i by nine when a door is already there.
        for (int i = 0; i < roomsToSpawn * 3; i++)
        {
            chosenRoom = RandomRoom();

            Vector2 chosen = RandomNotEmpty(chosenRoom);
            if (!chosenRoom.adjRoomsDict.ContainsKey(chosen))
            {
                i += 9;
            }
            SetAdj(chosenRoom, chosen, get(chosenRoom.Index + chosen));
        }

        minimapScript.PlayerEntersRoom(new Vector2(0, 0), get(new Vector2(0, 0)).adjRoomsDict.Keys.ToList());

        // add pathfinding graph and webs
        foreach (RoomControl room in roomsDict.Values)
        {
            room.PopulateCells();
            room.AddGraph();
            if (room.spawnWebs)
            {
                room.AddWebs(web, UnityEngine.Random.Range(minWebs, maxWebs));
            }
        }

        AstarPath.active.Scan();

        // populate rooms

        int totalTickets = enemyCommonness.Sum();

        for (int i = 0; i < totalEnemies; i++)
        {
            int c = 0;
            do
            {
                chosenRoom = RandomRoom();
                if (c > 1000)
                {
                    throw new System.Exception("Infinite loop occuring.");
                }
                c++;
            } while (chosenRoom.enemies.Count >= maxEnemiesPerRoom || chosenRoom.spawnEnemies == false);

            int ticket = UnityEngine.Random.Range(0, totalTickets);

            int hopeful = 0;
            int sum     = enemyCommonness[hopeful];

            while (sum <= ticket)
            {
                hopeful++;
                sum += enemyCommonness[hopeful];
            }
            // With ramp method used to ensure scaling is performed.
            chosenRoom.AddEnemyWithRamp(enemies[hopeful], ramp);
        }
        aStarGrids.Scan();
    }
Ejemplo n.º 19
0
	// Use this for initialization
	void Start ()
	{


		// initialize lists
		checkpoint_Transforms = new List<Transform> ();
		checkpoint_Objects = new List<GameObject> ();
		patrol_Transforms = new List<Transform> ();
		patrol_Scripts = new List<Patrol> ();
		score_Texts = new List<GUIText> ();
		remaining_Texts = new List<GUIText> ();

		// build the level
		level_End = false;
		string[][] currentLevel = ReadLevel (LevelFile);
		BuildLevel (currentLevel);
		string[][] currentEntities = ReadLevel (EntityFile);
		BuildEntities (currentEntities);

		// select our checkpoints
		ChooseCheckpoints ();
		Debug.Log (checkpoint_Objects.Count);

		// get components and objects

		compass = player_Transform.Find ("camera_main/compass").GetComponent<Compass> ();
		audio_Controller_Script = AudioControllerObject.GetComponent<AudioController> ();
		audio_Controller_Script.FadeSpeed = FadeSpeed;
		scene_Fader = FindObjectOfType<GUITexture> ().GetComponent<SceneFadeInOut> ();
		scene_Fader.FadeSpeed = FadeSpeed;

		// initialize the pathfinder

		a_Star_Path = Astar.GetComponent<AstarPath> ();
		a_Star_Path.UpdateGraphs (new Pathfinding.GraphUpdateObject ());
		a_Star_Path.Scan ();

		// build the patrollers - this needs to be done after the pathfinder is up

		string[][] currentPatrols = ReadLevel (PatrolFile);
		BuildPatrols (currentPatrols);
		foreach (Patrol current_patrol in patrol_Scripts) {
			current_patrol.FadeSpeed = FadeSpeed;
		}

		// set the first checkpoint
		next_Checkpoint = 0;
		checkpoint_Objects [next_Checkpoint].SetActive (true);

		// setup GUI

		foreach (GUIText text in FindObjectsOfType<GUIText>()) {
			if (text.name.Contains ("text_score"))
				score_Texts.Add (text);
			if (text.name.Contains ("text_remaining"))
				remaining_Texts.Add (text);
		}

		RenderText ();
	}
Ejemplo n.º 20
0
    private void launchWave()
    {
        //Loading and instatation of the prefab of enemy
        GameObject enemy = Instantiate(Resources.Load("Avatar/MaceEnemy", typeof(GameObject))) as GameObject;

        enemy.SetActive(true);

        switch (waveNum)
        {
        case 1:     //First wave

            //Display the alert on the game
            DisplayAlert.Print("Manche " + waveNum);

            //Duplication
            GameObject enemy1_1 = Instantiate(enemy);
            GameObject enemy1_2 = Instantiate(enemy);
            GameObject enemy1_3 = Instantiate(enemy);
            path.Scan();
            //Move the objects to the spawn spot
            enemy1_1.transform.position = GameObject.Find("EnemySpawn1").transform.position;
            enemy1_2.transform.position = GameObject.Find("EnemySpawn2").transform.position;
            enemy1_3.transform.position = GameObject.Find("EnemySpawn3").transform.position;
            waveNum++;
            break;

        case 2:     //Second wave

            //Display the alert on the game
            DisplayAlert.Print("Manche " + waveNum);

            //Duplication
            GameObject enemy2_1 = Instantiate(enemy);
            GameObject enemy2_2 = Instantiate(enemy);
            GameObject enemy2_3 = Instantiate(enemy);
            resetHealth();
            //Move the objects to the spawn
            enemy2_1.transform.position = GameObject.Find("EnemySpawn1").transform.position;
            enemy2_2.transform.position = GameObject.Find("EnemySpawn2").transform.position;
            enemy2_3.transform.position = GameObject.Find("EnemySpawn3").transform.position;
            waveNum++;
            break;

        case 3:     //Boss wave

            //Display the alert on the game
            DisplayAlert.Print("Boss");

            resetHealth();
            launchBossWave();
            waveNum++;
            break;

        case 4:     //Won
            Debug.Log("[GameFlow.cs] WON !");
            if (levelNumber == 2)
            {
                SceneManager.LoadScene("gameSuccess", LoadSceneMode.Single);
            }
            else
            {
                SceneManager.LoadScene("levelSuccess", LoadSceneMode.Single);
            }
            break;
        }

        //We disable the instantiated enemy
        enemy.SetActive(false);
    }
Ejemplo n.º 21
0
 private void FixedUpdate()
 {
     graph.Scan();
 }
Ejemplo n.º 22
0
 //Rescans the pathing grid
 public void ScanPath()
 {
     aStarPath.Scan();
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Nastavi graf pro pathfinding tak aby pokryval celou vygenerovanou mapu
        /// </summary>
        public void UpdatePathfinding(Vector3 center, int tilesPerRegionX, int tilesPerRegionY, int mapWidth, int mapHeight)
        {
            AstarPath ap = Controller.GetComponent <AstarPath>();

            foreach (IUpdatableGraph g in AstarPath.active.astarData.GetUpdateableGraphs())
            {
                if (g is GridGraph)
                {
                    GridGraph gridGraph = g as GridGraph;

                    if (detailedPathfinding)
                    {
                        gridGraph.erosionUseTags  = true;
                        gridGraph.erosionFirstTag = 1;
                        gridGraph.erodeIterations = 2;
                        gridGraph.nodeSize        = 0.5f;
                    }
                    else
                    {
                        gridGraph.erosionUseTags  = true;
                        gridGraph.erosionFirstTag = 1;
                        gridGraph.erodeIterations = 1;
                        gridGraph.nodeSize        = 0.75f;
                    }

                    float tileSize = gridGraph.nodeSize;
                    int   nodesX;
                    int   nodesY;

                    if (detailedPathfinding)
                    {
                        nodesX = (int)(10 + mapWidth * (1 - tileSize + 1 * tilesPerRegionX)) * 2;
                        nodesY = (int)(10 + mapHeight * (1 - tileSize + 1 * tilesPerRegionY)) * 2;
                    }
                    else
                    {
                        nodesX = (int)(10 + mapWidth * (tileSize * tilesPerRegionX)) * 2;
                        nodesY = (int)(10 + mapHeight * (tileSize * tilesPerRegionY)) * 2;
                    }


                    gridGraph.Width = nodesX;
                    gridGraph.Depth = nodesY;

                    gridGraph.center = center + new Vector3(nodesX / 2f * tileSize - 3, nodesY / 2f * tileSize - 3, 0);

                    //gridGraph.center = new Vector3(51, 51, 0);
                    gridGraph.UpdateSizeFromWidthDepth();
                }
            }

            ap.Scan();

            if (disableWallNodes)
            {
                foreach (IUpdatableGraph g in AstarPath.active.astarData.GetUpdateableGraphs())
                {
                    if (g is GridGraph)
                    {
                        GridGraph gridGraph = g as GridGraph;

                        foreach (GraphNode n in gridGraph.nodes)
                        {
                            if (n.Area == 1)
                            {
                                n.Tag      = 2;
                                n.Walkable = false;
                            }
                        }
                    }
                }
            }

            Controller.WaitForPathfindingError();
        }
Ejemplo n.º 24
0
 // Use this for initialization
 void Start()
 {
     CollectAllWaypoints();
     aStar.Scan();
 }
Ejemplo n.º 25
0
    IEnumerator Delayer()
    {
        //INSTANTIATE TILE SPAWNER//
        for (int i = 0; i < floorList.Count; i++)
        {
            GameObject goTileSpawner = Instantiate(tilespawnerPrefab, floorList[i], Quaternion.identity) as GameObject;
            goTileSpawner.name = tilespawnerPrefab.name;
            goTileSpawner.transform.SetParent(transform);
        }
        //INSTANTIATE TILE SPAWNER//

        //WAIT UNTILL TILESPAWNERS ARE GONE AND MAP IS GENERATED//
        while (FindObjectsOfType <TileSpawner>().Length > 0)
        {
            yield return(null);
        }
        //THIS PART IS FOR OPTIMIZATION//
        //WAIT UNTILL TILESPAWNERS ARE GONE AND MAP IS GENERATED//



        gg        = AstarPath.active.data.gridGraph;
        gg.center = new Vector3((maxX + minX) / 2, (maxY + minY) / 2, 0);

        /*
         * gg.width = System.Math.Abs((int)minX) + System.Math.Abs((int)maxX);
         * gg.depth = System.Math.Abs((int)minY)+ System.Math.Abs((int)maxY);
         */

        pathfinder.Scan();


        int count = 0;

        //THIS IS FOR CALCULATING THE WALLS AND THEIR SIDES//
        for (int x = (int)minX - 2; x <= (int)maxX + 2; x++)
        {
            for (int y = (int)minY - 2; y <= (int)maxY + 2; y++)
            {
                floorHit = Physics2D.OverlapBox(new Vector2(x, y), Vector2.one * 0.8f, 0, FloorMask);
                if (floorHit)
                {
                    if (!Vector2.Equals(floorHit.transform.position, floorList[floorList.Count - 1]))
                    {
                        TopHit   = Physics2D.OverlapBox(new Vector2(x, y + 1), Vector2.one * 0.8f, 0, WallMask);
                        RightHit = Physics2D.OverlapBox(new Vector2(x + 1, y), Vector2.one * 0.8f, 0, WallMask);
                        LeftHit  = Physics2D.OverlapBox(new Vector2(x - 1, y), Vector2.one * 0.8f, 0, WallMask);
                        DownHit  = Physics2D.OverlapBox(new Vector2(x, y - 1), Vector2.one * 0.8f, 0, WallMask);

                        //ınstantiateItems(TopHit, RightHit, DownHit, LeftHit);
                        InstantiateEnemies(TopHit, RightHit, DownHit, LeftHit);
                    }
                }
            }
        }
        ////THIS IS FOR CALCULATING THE WALLS AND THEIR SIDES//

        ///INSTANTIATE DOOR TO THE LAST FLOOR SPAWNED//
        InstantiateDoorway();
        ///INSTANTIATE DOOR TO THE LAST FLOOR SPAWNED//
    }
Ejemplo n.º 26
0
 // Update is called once per frame
 void FixedUpdate()
 {
     Debug.Log("Scanning");
     path.Scan();
 }
Ejemplo n.º 27
0
 private void UpdateGraph()
 {
     pathSettings.Scan(PathGrid);
 }
Ejemplo n.º 28
0
    /*IEnumerator GenerateLevel()
     * {
     *      for(int i = 0; i < tileAmount; i ++)
     *      {
     *              float dir = Random.Range(0f, 1f);
     *              int tile = Random.Range(0, themes[0].environments[0].environmentPrefabs.Length);
     *
     *              CreateTile(tile);
     *              CallMoveGenerator(dir);
     *
     *              yield return new WaitForSeconds(waitTime);
     *
     *              if(i == tileAmount - 1)
     *              {
     *                      Finish();
     *
     *                      CreateWallsBoarder();
     *
     *                      TestDistance();
     *
     *                      SpawnDoor();
     *
     *                      SpawnPlayer();
     *
     *                      SpawnChester();
     *
     *      SpawnConsole();
     *
     *                      SpawnObjects();
     *
     *                      SpawnEnemy();
     *
     *                      CreateTraps();
     *
     *                      PathFindingScan();
     *
     *                      Camera.main.GetComponent<CameraFollow>().target = GameObject.FindWithTag("Player").transform;
     *              }
     *      }
     * }*/

    void PathFindingScan()
    {
        Astar.Scan();
    }
Ejemplo n.º 29
0
    private IEnumerator UpdateGraphRoutine(NavMeshGraph graph)
    {
        updateInProgress = true;

        pathing.AddWorkItem(() =>
        {
            UnstitchFromNeighbors(graph);
        });

        pathing.FlushWorkItems();
        while (pathing.IsAnyWorkItemInProgress)
        {
            yield return(null);
        }

        if (toRemove.Contains(graph))
        {
            pathing.data.RemoveGraph(graph);


            toRemove.Remove(graph);
        }

        else
        {
            while (pathing.isScanning)
            {
                yield return(null);
            }
            pathing.Scan(graph);
            while (pathing.isScanning)
            {
                yield return(null);
            }



            pathing.AddWorkItem(() =>
            {
                StitchToNeighbors(graph);
            });
            pathing.FlushWorkItems();

            while (pathing.IsAnyWorkItemInProgress)
            {
                yield return(null);
            }

            if (!lastUpdate.ContainsKey(graph))
            {
                lastUpdate.Add(graph, Time.time);
            }
            else
            {
                lastUpdate[graph] = Time.time;
            }
        }

        updateInProgress = false;
        if (updateQueue.Count > 0)
        {
            StartCoroutine(UpdateGraphRoutine(updateQueue.Dequeue()));
        }
    }
Ejemplo n.º 30
0
 public void UpdateGraph()
 {
     Graph.Scan();
 }
Ejemplo n.º 31
0
    /// Start generates the rooms adds enemies, boss, webs and minimap
    void Start()
    {
        // These variables will change their meaning over the course of the method bu
        RoomControl thisRoom;
        RoomControl adjRoom;
        RoomControl chosenRoom;
        Vector2     roomVector;
        Vector2     roomVectorRel;

        if (seed == "")
        {
            // Generate seed if there was none given
            actseed = System.Environment.TickCount;
        }
        else
        {
            // Assign seed based on specified values
            string[] parts = seed.ToString().Split('#');
            actseed           = Int32.Parse(parts[0]);
            roomsToSpawn      = Int32.Parse(parts[1]);
            totalEnemies      = Int32.Parse(parts[2]);
            maxEnemiesPerRoom = Int32.Parse(parts[3]);
            minWebs           = Int32.Parse(parts[4]);
            maxWebs           = Int32.Parse(parts[5]);
        }
        UnityEngine.Random.seed = actseed;

        // Reference to the minimap, so it can be generated in unison with the actual floor
        MinimapScript minimapScript = minimapUI.GetComponent <MinimapScript>();

        // Start room
        thisRoom           = ((GameObject)Instantiate(roomPrefab, new Vector3(0, 0, 0), Quaternion.identity)).GetComponent <RoomControl>();
        thisRoom.minimapUI = minimapUI;
        thisRoom.Floor     = startPrefab;     // pick set floor

        thisRoom.Index = new Vector2(0, 0);
        minimapScript.GenerateMapBlock(thisRoom.Index);

        roomsDict.Add(thisRoom.Index, thisRoom);

        thisRoom.gameObject.name = "Room " + 0;
        thisRoom.spawnEnemies    = false;      // first room should be safe
        thisRoom.spawnWebs       = false;

        thisRoom.gameObject.transform.Find("Lights").gameObject.SetActive(true);

        // Normal rooms
        // First room and boss room are counted in "roomsToSpawn", but aren't done in this loop.
        for (int i = 1; i < roomsToSpawn - 1; i++)
        {
            int a = 0;
            do               // Find empty room to put the new room adjacent to
            {
                adjRoom = RandomRoom();
                if (a > 1000)
                {
                    throw new System.Exception("Infinite loop occuring.");
                }
                a++;
            } while (!IsNextToEmpty(adjRoom));

            roomVectorRel = RandomEmpty(adjRoom);
            roomVector    = adjRoom.Index + roomVectorRel;

            thisRoom           = ((GameObject)Instantiate(roomPrefab, RoomControl.IndexToPosition(roomVector), Quaternion.identity)).GetComponent <RoomControl>();
            thisRoom.minimapUI = minimapUI;
            thisRoom.Floor     = floorPrefabs[UnityEngine.Random.Range(0, floorPrefabs.Count)];
            thisRoom.Index     = roomVector;
            minimapScript.GenerateMapBlock(thisRoom.Index);
            thisRoom.gameObject.name = "Room " + i;

            SetAdj(adjRoom, roomVectorRel, thisRoom);

            roomsDict.Add(thisRoom.Index, thisRoom);
        }

        // Boss room
        int b = 0;

        do           // Find empty room to put the new room adjacent to
        {
            adjRoom = RandomRoom();
            if (b > 1000)
            {
                throw new System.Exception("Infinite loop occuring.");
            }
            b++;
        } while (!IsNextToEmpty(adjRoom));

        roomVectorRel = RandomEmpty(adjRoom);
        roomVector    = adjRoom.Index + roomVectorRel;

        thisRoom           = ((GameObject)Instantiate(roomPrefab, RoomControl.IndexToPosition(roomVector), Quaternion.identity)).GetComponent <RoomControl>();
        thisRoom.minimapUI = minimapUI;
        thisRoom.Floor     = bossFloor;
        thisRoom.Index     = roomVector;
        minimapScript.GenerateMapBlock(thisRoom.Index);
        thisRoom.gameObject.name = "Boss Room";

        thisRoom.spawnEnemies = false;

        SetAdj(adjRoom, roomVectorRel, thisRoom);

        roomsDict.Add(thisRoom.Index, thisRoom);

        // Special stuff for each boss. Should be refactored
        if (boss.transform.name == "Boss3")
        {
            int temp1 = UnityEngine.Random.Range(-18, 18);
            int temp2 = UnityEngine.Random.Range(-10, 10);
            boss = (GameObject)Instantiate(boss, thisRoom.transform.position + new Vector3(temp1, 2, temp2), Quaternion.identity);
            BossThree bs3 = boss.GetComponent <BossThree> ();
            bs3.roomCont = thisRoom.GetComponent <RoomControl> ();
        }
        else if (boss.transform.name == "FlyBoss" || boss.transform.name == "FlyBossTest")
        {
            boss = (GameObject)Instantiate(boss, thisRoom.transform.position + new Vector3(0, 4, 0), Quaternion.identity);
            boss.GetComponent <EnemyControl>().home = thisRoom.transform;
            boss.GetComponent <AIPath>().enabled    = false;         // Flying bosses movement is disable until the player enters the room
        }
        else
        {
            boss = (GameObject)Instantiate(boss, thisRoom.transform.position + new Vector3(0, 2, 0), Quaternion.identity);
        }
        boss.GetComponent <AIPath>().target = GameObject.FindWithTag("Player").transform;
        thisRoom.AddBoss(boss);

        // link rooms
        // The room adding loop above does not allow loops. Here extra doors are added so that there can be loops.
        // Depending on level layout, extra doors may not be addable.
        // Loop finds two adjacent rooms. If there is no door already there, a door is added and loop var incremented by one
        // If there already was a door, increment by 0.1
        // This means there will never be an infinite loop
        for (float i = 0f; i < roomsToSpawn / 3.3f; i += 0.1f)
        {
            chosenRoom = RandomRoom();

            Vector2 chosen = RandomNotEmpty(chosenRoom);
            if (!chosenRoom.adjRoomsDict.ContainsKey(chosen))
            {
                i += 0.9f;
            }
            SetAdj(chosenRoom, chosen, get(chosenRoom.Index + chosen));
        }

        minimapScript.PlayerEntersRoom(new Vector2(0, 0), get(new Vector2(0, 0)).adjRoomsDict.Keys.ToList());

        // add pathfinding graph and webs
        foreach (RoomControl room in roomsDict.Values)
        {
            room.PopulateCells();
            room.AddGraph();
            if (room.spawnWebs)
            {
                room.AddWebs(web, UnityEngine.Random.Range(minWebs, maxWebs));
            }
        }

        // Sets up the pathfinding based on the generated map
        AstarPath.active.Scan();

        // Modify total enemies so that it is a legal value
        int maxLegalEnemies = (roomsToSpawn - 2) * maxEnemiesPerRoom;

        if (totalEnemies > maxLegalEnemies)
        {
            totalEnemies = maxLegalEnemies;
        }
        if (totalEnemies < 0)
        {
            totalEnemies = 0;
        }


        // Populate rooms
        // A room is randomly chosen with equal probability, so long as the room doesn't have too many already
        // A raffle is held on the enemy types to decide which enemy type spawns.
        // enemyCommonness decides how many tickets that enemy type has
        // Winning ticket is chosen and we iterate over the enemy types till we find the winner

        int totalTickets = enemyCommonness.Sum();

        for (int i = 0; i < totalEnemies; i++)
        {
            int c = 0;
            do
            {
                chosenRoom = RandomRoom();
                if (c > 1000)
                {
                    throw new System.Exception("Infinite loop occurring.");
                }
                c++;
            } while (chosenRoom.enemies.Count >= maxEnemiesPerRoom || chosenRoom.spawnEnemies == false);

            int winningTicket = UnityEngine.Random.Range(0, totalTickets);

            int hopeful = 0;
            int sum     = enemyCommonness[hopeful];

            while (sum <= winningTicket)
            {
                hopeful++;
                sum += enemyCommonness[hopeful];
            }

            chosenRoom.AddEnemy(enemies[hopeful]);
        }
        // Generate seed for recreate
        seed = actseed.ToString() + "#" + roomsToSpawn.ToString() + "#" + totalEnemies.ToString()
               + "#" + maxEnemiesPerRoom.ToString() + "#" + minWebs.ToString() + "#" + maxWebs.ToString() + "#" + Application.loadedLevelName;
        aStarGrids.Scan();
    }
Ejemplo n.º 32
0
    private void GenerateMap()
    {
        //setando custo
        int costForEnemies = globalMapSettings.totalEntitiesCost;

        //limpar mapa antigo se houver
        if (roomParent != null)
        {
            Destroy(roomParent);
        }
        roomParent = new GameObject("RoomRoot");
        roomParent.transform.position = Vector3.zero;
        MapRoom targetRoom = null;

        //colocando base
        if (currentRoomIndex < (float)(globalMapSettings.numberOfRooms) / 2.00f)
        {
            targetRoom = globalMapSettings.startRoomSet.GetRandomRoom();
        }
        else
        {
            targetRoom = globalMapSettings.endRoomSet.GetRandomRoom();
        }
        //se currentIndex = 2, usar sala quest[0], se quest.count = 10, ultima quest fica em quest[9], valor maximo pro curIndex de quest seria entao 11
        if (currentRoomIndex >= 2 && currentRoomIndex <= questRooms.Count + 1)
        {
            targetRoom = questRooms[currentRoomIndex - 2];
        }

        GameObject roomBase = Instantiate(targetRoom.roomBase, Vector3.zero, Quaternion.identity, roomParent.transform);

        //escolhendo e colocando decoracao
        MapDecoration decoration = Instantiate <MapDecoration>(targetRoom.GetRandomDecoration(), Vector3.zero, Quaternion.identity, roomParent.transform);

        decoration.ClearPointers();
        currentDeco = decoration;
        //configurando portas
        if (decoration.doors == null)
        {
            decoration.doors = new MapDoor[0];
        }
        for (int i = 0; i < decoration.doors.Length; i++)
        {
            decoration.doors[i].SetLocked(true);
            decoration.doors[i].SetupDoor(this, GetRandomReward());
        }

        //spawn de inimigos
        MapEnemySet targetSet = currentRoomIndex <= (float)globalMapSettings.numberOfRooms / 2 ?
                                globalMapSettings.startEnemySet : globalMapSettings.endEnemySet;

        if (decoration.pointers == null)
        {
            decoration.pointers = new MapPointer[0];
        }
        for (int i = 0; i < decoration.pointers.Length; i++)
        {
            MapPointer randomPointer = decoration.GetRandomAvailablePointer();
            //verifica todos inimigos possiveis para esse ponto e pega um aleatorio
            if (randomPointer == null)
            {
                break; //sair do for por falta de pontos
            }
            MapEntity targetEntity = targetSet.GetRandomEntity(globalMapSettings.mapDifficulty,
                                                               randomPointer.pointSize, costForEnemies);
            if (targetEntity != null)
            {
                costForEnemies -= targetEntity.entityCost;
                MapEntity spawnedEntity = Instantiate <MapEntity>(targetEntity,
                                                                  randomPointer.transform.position,
                                                                  Quaternion.identity, roomParent.transform);
                randomPointer.used = true;
            }
        }

        playerObject.transform.position = decoration.playerSpawn.position;
        UpdateRoomCounter();
        path.Scan();
    }
Ejemplo n.º 33
0
 private void ScanMap(Dimension dim)
 {
     pathGraph.Scan();
 }