コード例 #1
0
ファイル: UnitController.cs プロジェクト: v-free/hexMap
    private void HighlightPath(IEnumerable <IPathNode <HexNode> > path)
    {
        if (path == null)
        {
            return;
        }

        Dictionary <ITile, bool> tiles = new Dictionary <ITile, bool>();

        IEnumerator <IPathNode <HexNode> > enumerator = path.GetEnumerator();

        //enumerator.MoveNext(); // Skips first //
        //tiles.Add(enumerator.Current.GetNode().Tile, true);

        while (enumerator.MoveNext())
        {
            IPathNode <HexNode> node    = enumerator.Current;
            HexNode             hexNode = node.GetNode();
            ITile tile = hexNode.Tile;

            if (tiles.ContainsKey(tile))
            {
                continue;
            }
            tiles.Add(tile, true);

            Vector3    position = new Vector3(tile.PosX, tile.PosY + 0.05f, tile.PosZ);
            Quaternion rotation = Quaternion.Euler(90, hexNode.Direction.DirectionRotation() - 90, 0);

            GameObject highlight = Instantiate(pathArrowPrefab, position, rotation, transform);
            highlightedPath.Add(highlight);
            lastPathArrowRotation = rotation;
        }
    }
コード例 #2
0
    void Start()
    {
        node = GetComponent <HexNode>();
        grid = GameObject.FindObjectsOfType <HexGrid>()[0];

        Clickable c = GetComponent <Clickable>();

        c.Click += (Clickable sender) =>
        {
            HexNode[,] nodes = this.grid.GetNodes();
            for (int x = 0; x < nodes.GetLength(0); x++)
            {
                for (int y = 0; y < nodes.GetLength(1); y++)
                {
                    nodes[x, y].ResetColor();
                }
            }

            this.node.SetSelected();
            List <HexNode> nodesInRange = this.grid.GetWithinRange(this.node.gridPosition.x, this.node.gridPosition.y, this.selectRange);
            foreach (HexNode node in nodesInRange)
            {
                node.SetHighlighted();
            }
        };
    }
コード例 #3
0
    public void CreateGrid()
    {
        Nodes      = new HexNode[width, height];
        worldNodes = new WorldNode[width, height];

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                bool       offset = false;
                GameObject go     = new GameObject("Node : " + x + ", " + y); //GameObject.CreatePrimitive(PrimitiveType.Sphere);
                go.transform.parent = this.transform;
                if (y % 2 == 1)
                {
                    go.transform.position = new Vector3(x + radialOffest, y, 0);
                    offset = true;
                }
                else
                {
                    go.transform.position = new Vector3(x, y, 0);
                }

                worldNodes[x, y] = go.AddComponent <WorldNode>();
                HexNode newNode = new HexNode(x, y, offset);
                Nodes[x, y] = newNode;
                worldNodes[x, y].hexNode = newNode;
                //Debug.Log("node " +x+ " ," +y+ " has this many neighbours --> " +newNode.GetNeighbours().Count);
            }
        }
    }
コード例 #4
0
        private static IActor CreateActor(IMap map, HexNode startNode)
        {
            var playerMock = new Mock <IPlayer>();
            var player     = playerMock.Object;

            var personMock = new Mock <IPerson>();

            personMock.SetupGet(x => x.PhysicalSize).Returns(PhysicalSize.Size1);
            var person = personMock.Object;

            IGraphNode currentNode = startNode;
            var        actorMock   = new Mock <IActor>();

            actorMock.SetupGet(x => x.Node).Returns(() => currentNode);
            actorMock.Setup(x => x.MoveToNode(It.IsAny <IGraphNode>()))
            .Callback <IGraphNode>(node => currentNode = node);
            // ReSharper disable once UnusedVariable
            var actor = actorMock.Object;

            // Исправить и убрать отключение инспекции для actor.

            var actor2 = new Actor(person, player, startNode);

            map.HoldNode(startNode, actor2);
            return(actor2);
        }
コード例 #5
0
    /// <summary>
    /// Returns a List of all HexNodes that are within 'range' of the specified coordinate (except itself)
    /// </summary>
    /// <param name="xCoord"></param>
    /// <param name="yCoord"></param>
    /// <param name="range"></param>
    /// <returns></returns>
    public List <HexNode> GetWithinRange(int xCoord, int yCoord, int range)
    {
        List <HexNode> inRange  = new List <HexNode>();
        HexNode        baseNode = GetNode(xCoord, yCoord);

        if (baseNode == null)
        {
            return(null);
        }

        HexNode currentNode = null;

        for (int x = -range; x <= range; x++)
        {
            for (int y = -range; y <= range; y++)
            {
                if (Mathf.Abs(x + y) > range)
                {
                    continue;                           // "cut out the corners"
                }
                if (x == 0 && y == 0)
                {
                    continue;                   // skip basenode itself
                }
                currentNode = GetNode(xCoord + x, yCoord + y);
                if (currentNode != null)
                {
                    inRange.Add(currentNode);
                }
            }
        }
        return(inRange);
    }
コード例 #6
0
    private void Update()
    {
        // Spawn a grid of prefabs!
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (!this.spawned)
            {
                this.spawned = true;
                SpawnNodes();
            }
        }

        // Select [3,3] and highlight everything in 1 range!
        if (Input.GetKeyDown(KeyCode.LeftAlt))
        {
            HexNode selectedNode = GetNode(3, 3);
            selectedNode.SetSelected();

            List <HexNode> adjacentNodes = GetWithinRange(3, 3, 2);
            foreach (HexNode n in adjacentNodes)
            {
                n.SetHighlighted();
            }
        }
    }
コード例 #7
0
ファイル: TestScript.cs プロジェクト: hschneidman/NewCatan
	void Start () {
		hx = new HexNode();
		hx.initCoords(0,0);
		hx.addHexNbrs();
		HexNode[] hhh = new HexNode[hx.HexNbrs.Count];
		hx.HexNbrs.Values.CopyTo(hhh,0);
		foreach(HexNode h in hhh){
            h.addHexNbrs();
        }
		foreach(HexNode h in NodeHolder.instance().HexList.Values){
			GameObject go = GameObject.Instantiate(hex);
			go.transform.position = h.coordTransform();
			h.addSettNbrs();
/*			Debug.Log ("Hex at " + h.coords.asString() + " with neighbours at " +
			           h.HexNbrs[0].coords.asString() + ", " + 
			           h.HexNbrs[1].coords.asString() + ", " + 
			           h.HexNbrs[2].coords.asString() + ", " + 
			           h.HexNbrs[3].coords.asString() + ", " + 
			           h.HexNbrs[4].coords.asString() + ", " + 
			           h.HexNbrs[5].coords.asString() + ", ");*/
		}
		foreach(SettNode s in NodeHolder.instance().SettList.Values){
			GameObject whamo = GameObject.Instantiate(sett);
			whamo.transform.position = s.coordTransform();
		}

	}
コード例 #8
0
        private void CreateOneRoomNodes(ISectorMap map, HashSet <string> edgeHash, Room room, Size cellSize)
        {
            var interiorObjects = _randomSource.RollInteriorObjects(room.Width, room.Height);

            for (var x = 0; x < room.Width; x++)
            {
                for (var y = 0; y < room.Height; y++)
                {
                    var nodeX = x + room.PositionX * cellSize.Width;
                    var nodeY = y + room.PositionY * cellSize.Height;

                    var isObstacle          = false;
                    var interiorObjectMetas = interiorObjects
                                              .SingleOrDefault(o => o.Coords.CompsEqual(x, y));

                    if (interiorObjectMetas != null)
                    {
                        //TODO Сделать так, чтобы укрытия не генерировались на узлах с выходами
                        // Как вариант - если выбираем узел, как выход, то снимаем флаг укрытия.
                        // Вообще, нужно поискать алгоритмы, которые бы расставляли укрытия и выходы, оставляя комнату проходимой.
                        isObstacle = true;
                    }

                    var node = new HexNode(nodeX, nodeY, isObstacle);

                    room.Nodes.Add(node);
                    map.AddNode(node);

                    RoomHelper.AddAllNeighborToMap(map, edgeHash, room, node);
                }
            }

            CreateTransitions(map, room);
        }
コード例 #9
0
ファイル: TestScript.cs プロジェクト: bradparks/CatanUnity
    void Start()
    {
        hx = new HexNode();
        hx.initCoords(0, 0);
        hx.addHexNbrs();
        HexNode[] hhh = new HexNode[hx.HexNbrs.Count];
        hx.HexNbrs.Values.CopyTo(hhh, 0);
        foreach (HexNode h in hhh)
        {
            h.addHexNbrs();
        }
        foreach (HexNode h in NodeHolder.instance().HexList.Values)
        {
            GameObject go = GameObject.Instantiate(hex);
            go.transform.position = h.coordTransform();
            h.addSettNbrs();

/*			Debug.Log ("Hex at " + h.coords.asString() + " with neighbours at " +
 *                                 h.HexNbrs[0].coords.asString() + ", " +
 *                                 h.HexNbrs[1].coords.asString() + ", " +
 *                                 h.HexNbrs[2].coords.asString() + ", " +
 *                                 h.HexNbrs[3].coords.asString() + ", " +
 *                                 h.HexNbrs[4].coords.asString() + ", " +
 *                                 h.HexNbrs[5].coords.asString() + ", ");*/
        }
        foreach (SettNode s in NodeHolder.instance().SettList.Values)
        {
            GameObject whamo = GameObject.Instantiate(sett);
            whamo.transform.position = s.coordTransform();
        }
    }
コード例 #10
0
 public override void BeginState()
 {
     Agent.SetWalkAnimation(true);
     _targetNode          = Agent.WalkPath[0];
     _targetRotation      = Quaternion.LookRotation(_targetNode.Position - Agent.Position);
     _rotationAccumulator = 0.0f;
 }
コード例 #11
0
        /// <summary>
        /// Проверяем, что к сундуку есть подход.
        /// </summary>
        private static void ValidatePassability(
            HexNode currentContainerHex,
            ISectorMap sectorMap,
            IGraphNode[] allContainerNodes)
        {
            var neighborNodes   = sectorMap.GetNext(currentContainerHex);
            var hasFreeNeighbor = false;

            foreach (var neighborNode in neighborNodes)
            {
                var neighborHex = (HexNode)neighborNode;

                var isContainer = allContainerNodes.Contains(neighborHex);

                if (!isContainer)
                {
                    hasFreeNeighbor = true;
                    break;
                }
            }

            if (!hasFreeNeighbor)
            {
                throw new SectorValidationException($"Контейнер {currentContainerHex} не имеет подступов.");
            }
        }
コード例 #12
0
        public override void Update()
        {
            if (!_finishedSelection)
            {
                HexNode playerNode = _player.GetCurrentNode();
                HexNode enemyNode  = Enemy.GetCurrentNode();

                Manager.Pathfinder.Search(enemyNode, playerNode);
                List <HexNode> path = Manager.Pathfinder.Path;

                if (path != null)
                {
                    SelectInteraction(path, playerNode);
                }
                else
                {
                    Debug.Log("no valid path was found! for " + Enemy.name);
                    _finishedSelection = true;
                }
            }
            else
            {
                Manager.ChangePhase(typeof(TurnPhaseEnemyAction));
            }
        }
コード例 #13
0
    public void Search(HexNode start, int expansionLimit)
    {
        _done           = false;
        start.Expansion = 0;
        _frontier       = new Queue <HexNode>();
        _frontier.Enqueue(start);

        _visited = new HashSet <HexNode>();
        _visited.Add(start);

        while (_frontier.Count > 0)
        {
            HexNode current = _frontier.Dequeue();

            foreach (HexNode next in current.Neighbors)
            {
                if (!_visited.Contains(next))
                {
                    next.Expansion = current.Expansion + 1;
                    if (next.Expansion < expansionLimit)
                    {
                        _frontier.Enqueue(next);
                        _visited.Add(next);
                    }
                }
            }
        }
        _done = true;
    }
コード例 #14
0
 private void Start()
 {
     _manager           = Manager.GetComponent <HexNodesManager>();
     _node              = _manager.ReturnClosestHexNode(transform.position);
     transform.position = _node.Position;
     _manager.RegisterRadationTile(this);
 }
コード例 #15
0
        private void MouseClick(Ray mouseRay)
        {
            if (Input.GetMouseButtonDown(0))
            {
                Debug.Log(Player.CurrentNode.Index);
                RaycastHit mouseClickHit;

                if (Physics.Raycast(mouseRay, out mouseClickHit))
                {
                    if (mouseClickHit.collider.CompareTag("selectionhex"))
                    {
                        var hex = mouseClickHit.transform.GetComponent <SelectionHexRenderer>();

                        if (hex != null)
                        {
                            HexNode hexNode = hex.GetUnderlyingNode();

                            Manager.Pathfinder.Search(Player.CurrentNode, hexNode);
                            Debug.Log(Manager.Pathfinder);
                            List <HexNode> path = Manager.Pathfinder.Path;

                            if (path != null)
                            {
                                SelectInteraction(path, hexNode);
                            }
                        }
                    }
                }
            }
        }
コード例 #16
0
    public void SetNodesFromInfoContainer(HexCellInfoContainer[] infoContainers, bool cullBadConnections = false)
    {
        // Debug.Log(infoContainers);

        HexNode[] nodes = new HexNode[infoContainers.Length];
        for (int i = 0; i < infoContainers.Length; i++)
        {
            nodes[i] = new HexNode(infoContainers[i]);
        }

        for (int i = 0; i < nodes.Length; i++)
        {
            List <HexNode> nodeNeighbors = new List <HexNode>();

            int[] nIndexes = infoContainers[i].NeighborIndexes;

            foreach (var nIndex in nIndexes)
            {
                nodeNeighbors.Add(nodes[nIndex]);
            }
            nodes[i].Neighbors = nodeNeighbors.ToArray();
        }

        if (cullBadConnections)
        {
            _nodes = CullBadConnections(nodes);
        }
        else
        {
            _nodes = nodes;
        }
    }
コード例 #17
0
        /// <summary>
        /// Преобразовывет черновые регионы в узлы реальной карты.
        /// </summary>
        private static void MapDraftRegionsToSectorMap(Matrix <bool> matrix, RegionDraft[] draftRegions, ISectorMap map)
        {
            var cellMap   = matrix.Items;
            var mapWidth  = matrix.Width;
            var mapHeight = matrix.Height;

            var regionNodeCoords = draftRegions.SelectMany(x => x.Coords);
            var hashSet          = new HashSet <OffsetCoords>(regionNodeCoords);

            for (var x = 0; x < mapWidth; x++)
            {
                for (var y = 0; y < mapHeight; y++)
                {
                    if (cellMap[x, y])
                    {
                        var offsetCoord = new OffsetCoords(x, y);

                        if (!hashSet.Contains(offsetCoord))
                        {
                            var node = new HexNode(x, y);
                            map.AddNode(node);
                        }
                    }
                }
            }
        }
コード例 #18
0
ファイル: GridMapGeneratorTests.cs プロジェクト: tgspn/Zilon
 private static Edge GetExistsEdge(IMap map, HexNode node, HexNode neighbor)
 {
     return((Edge)(from edge in map.Edges
                   where edge.Nodes.Contains(node)
                   where edge.Nodes.Contains(neighbor)
                   select edge).SingleOrDefault());
 }
コード例 #19
0
ファイル: RoomHelper.cs プロジェクト: leorik/Zilon_Roguelike
        /// <summary>
        /// Возвращает ребро, соединяющее указанные узлы.
        /// </summary>
        /// <param name="edgeHash"> Хеш ребер карты. </param>
        /// <param name="node"> Искомый узел. </param>
        /// <param name="neighbor"> Узел, с которым соединён искомый. </param>
        /// <returns> Ребро или null, если такого ребра нет на карте. </returns>
        public static bool IsExistsEdge(HashSet <string> edgeHash, HexNode node, HexNode neighbor)
        {
            if (edgeHash is null)
            {
                throw new System.ArgumentNullException(nameof(edgeHash));
            }

            if (node is null)
            {
                throw new System.ArgumentNullException(nameof(node));
            }

            if (neighbor is null)
            {
                throw new System.ArgumentNullException(nameof(neighbor));
            }

            var hashKey1 = $"{node}-{neighbor}";

            if (edgeHash.Contains(hashKey1))
            {
                return(true);
            }

            var hashKey2 = $"{neighbor}-{node}";

            return(edgeHash.Contains(hashKey2));
        }
コード例 #20
0
ファイル: RoomHelper.cs プロジェクト: leorik/Zilon_Roguelike
        /// <summary>
        /// Создаёт на карте ребро, соединяющее два узла этой карты.
        /// </summary>
        /// <param name="targetMap"> Целевая карта, для которой нужно создать ребро. </param>
        /// <param name="edgeHash"> Хеш ребер карты. </param>
        /// <param name="node"> Исходное ребро карты. </param>
        /// <param name="neighbor"> Соседнее ребро карты, с которым будет соединено исходное. </param>
        public static void AddEdgeToMap(IMap targetMap, HashSet <string> edgeHash, HexNode node, HexNode neighbor)
        {
            if (targetMap is null)
            {
                throw new System.ArgumentNullException(nameof(targetMap));
            }

            if (edgeHash is null)
            {
                throw new System.ArgumentNullException(nameof(edgeHash));
            }

            if (node is null)
            {
                throw new System.ArgumentNullException(nameof(node));
            }

            if (neighbor is null)
            {
                throw new System.ArgumentNullException(nameof(neighbor));
            }

            var hashKey1 = $"{node}-{neighbor}";

            edgeHash.Add(hashKey1);

            targetMap.AddEdge(node, neighbor);
        }
コード例 #21
0
    /// <summary>
    /// Adds a single hex to the character's mental map.
    /// </summary>
    /// <param name="hex">The hex to add.</param>
    public void UpdateMap(Hex hex)
    {
        HexNode hexNode;

        if (!map.ContainsKey(hex.position))
        {
            hexNode           = new HexNode(hex);
            map[hex.position] = hexNode;
        }
        else
        {
            hexNode = map[hex.position];
        }

        foreach (Hex neighbor in hex.neighbors)
        {
            if (!neighbor.walkable)
            {
                continue;
            }
            if (!map.ContainsKey(neighbor.position))
            {
                map[neighbor.position] = new HexNode(neighbor);
            }

            if (!hexNode.HasConnection(map[neighbor.position]))
            {
                hexNode.SetConnection(map[neighbor.position]);
            }
        }
    }
コード例 #22
0
        public IStaticObject Create(ISector sector, HexNode node, int id)
        {
            if (sector is null)
            {
                throw new ArgumentNullException(nameof(sector));
            }

            var staticObject = new StaticObject(node, Purpose, id);

            // Все залежи изначально имеют пустой модуль контейнера.
            // Он будет заполняться по мере добычи.
            var containerModule = new DepositContainer();

            staticObject.AddModule(containerModule);

            var dropScheme    = _schemeService.GetScheme <IDropTableScheme>(_dropTableSchemeSid);
            var depositModule = new PropDepositModule(containerModule, dropScheme, _dropResolver, _toolTags,
                                                      ExhausingValue, Difficulty);

            staticObject.AddModule(depositModule);

            var lifetimeModule = new DepositLifetimeModule(sector.StaticObjectManager, staticObject);

            staticObject.AddModule(lifetimeModule);

            var durabilityModule = new DepositDurabilityModule(depositModule, lifetimeModule, 10);

            staticObject.AddModule(durabilityModule);

            return(staticObject);
        }
コード例 #23
0
 /// <summary>
 /// Проверяем, что сундук не стоит на препятствии.
 /// </summary>
 private static void ValidateObstacleOverlap(HexNode hex)
 {
     if (hex.IsObstacle)
     {
         throw new SectorValidationException();
     }
 }
コード例 #24
0
        public void Setup()
        {
            int mapSize = 1000;
            int baseX   = 50;
            int baseY   = 50;

            _radius = 5;

            // ARRANGE

            var map = new SectorHexMap(1000);

            for (var i = 0; i < mapSize; i++)
            {
                for (var j = 0; j < mapSize; j++)
                {
                    var hexNode = new HexNode(i, j);
                    map.AddNode(hexNode);
                }
            }

            _fowData = new HumanSectorFowData();

            _baseNode = map.HexNodes.Single(x => x.OffsetCoords.X == baseX && x.OffsetCoords.Y == baseY);

            _fowContextMock = new TestFowContext(map);
        }
コード例 #25
0
ファイル: MapFiller.cs プロジェクト: luisvita/Zilon_Roguelike
        private static void CreateNodes(IMap map,
                                        int startX,
                                        int startY,
                                        int mapSize,
                                        OptionsDelegate optionsDelegate)
        {
            var nodeIdCounter = 1;

            for (var row = startY; row < startY + mapSize; row++)
            {
                for (var col = startX; col < startX + mapSize; col++)
                {
                    HexNodeOptions options;
                    if (optionsDelegate != null)
                    {
                        options = optionsDelegate(col, row);
                    }
                    else
                    {
                        options = new HexNodeOptions
                        {
                            IsObstacle = false
                        };
                    }

                    var node = new HexNode(col, row, options.IsObstacle)
                    {
                        Id = nodeIdCounter++
                    };

                    map.AddNode(node);
                }
            }
        }
コード例 #26
0
    /*
     *  Get all the nearby filtered neighbours
     */
    public List <HexNode> GetConnectedNodes(NodeType filteredNodeType)
    {
        List <HexNode> nodes = new List <HexNode>();

        int[] hitAngles = new int[6] {
            30, 90, 150, 210, 270, 330
        };


        for (int i = 0; i < hitAngles.Length; i++)
        {
            Vector3        direction = Quaternion.Euler(0, 0, hitAngles[i]) * Vector3.right;
            Ray            ray       = new Ray(this.transform.position, direction);
            RaycastHit2D[] rayHit    = Physics2D.RaycastAll(ray.origin, ray.direction, this.rayDistance);
            for (int k = 0; k < rayHit.Length; k++)
            {
                if (rayHit[k].collider.gameObject.tag == "HexNode" && rayHit[k].collider.gameObject != this.gameObject)
                {
                    HexNode hxNode = rayHit[k].collider.gameObject.GetComponent <HexNode>();
                    if (hxNode.nodeType == filteredNodeType)
                    {
                        nodes.Add(hxNode);
                    }
                }
            }
        }

        return(nodes);
    }
コード例 #27
0
        private static void CreateOneRoomNodes(IMap map, HashSet <string> edgeHash, Room room)
        {
            for (var x = 0; x < room.Width; x++)
            {
                for (var y = 0; y < room.Height; y++)
                {
                    var nodeX = x + room.PositionX * ROOM_CELL_SIZE;
                    var nodeY = y + room.PositionY * ROOM_CELL_SIZE;
                    var node  = new HexNode(nodeX, nodeY);
                    room.Nodes.Add(node);
                    map.Nodes.Add(node);

                    var neighbors = HexNodeHelper.GetNeighbors(node, room.Nodes);

                    foreach (var neighbor in neighbors)
                    {
                        var isExists = IsExistsEdge(edgeHash, node, neighbor);

                        if (!isExists)
                        {
                            AddEdgeToMap(map, edgeHash, node, neighbor);
                        }
                    }
                }
            }
        }
コード例 #28
0
ファイル: HexNode.cs プロジェクト: ErrorMee/HexFrame
    private void RecursiveRoute(HexNode node, List <HexNode> route)
    {
        route.Add(node);

        if (node.fromAdd != null)
        {
            if (node.routeAddFlage == false)
            {
                node.routeAddFlage = true;
                RecursiveRoute(node.fromAdd, route);
            }
            else
            {
                if (node.from != null)
                {
                    RecursiveRoute(node.from, route);
                }
            }
        }
        else
        {
            if (node.from != null)
            {
                RecursiveRoute(node.from, route);
            }
        }
    }
コード例 #29
0
ファイル: RoomHelper.cs プロジェクト: leorik/Zilon_Roguelike
        public static HexNode CreateCorridorNode(IMap map, HashSet <string> edgeHash, HexNode currentNode, int currentX, int currentY)
        {
            if (map is null)
            {
                throw new System.ArgumentNullException(nameof(map));
            }

            var node = map.Nodes.OfType <HexNode>()
                       .SingleOrDefault(x => x.OffsetCoords.X == currentX && x.OffsetCoords.Y == currentY);

            if (node == null)
            {
                node = new HexNode(currentX, currentY);
                map.AddNode(node);
            }

            var isExists = IsExistsEdge(edgeHash, node, currentNode);

            if (!isExists)
            {
                AddEdgeToMap(map, edgeHash, currentNode, node);
            }

            return(node);
        }
コード例 #30
0
ファイル: HexNode.cs プロジェクト: bradparks/CatanUnity
    public void addHexNbr(int location)
    {
        int x = this.coords.x;
        int y = this.coords.y;

        if (location != 3 && location != 0)
        {
            if (location < 3)
            {
                x++;
            }
            else
            {
                x--;
            }
        }
        if (location != 1 && location != 4)
        {
            if (location < 4 && location > 1)
            {
                y--;
            }
            else
            {
                y++;
            }
        }
        HexNbrs[location] = new HexNode();
        if (!HexNbrs[location].initCoords(x, y))
        {
            HexNbrs[location] = NodeHolder.instance().HexList[new Point(x, y)];
        }
        HexNbrs[location].HexNbrs[(location + 3) % 6] = this;
    }
コード例 #31
0
        private void SetInteractionState(HexNode target)
        {
            Player.InteractionTarget = target;

            if (target.HasEnemy)
            {
                Player.UpcomingInteractionState = typeof(PlayerStateInteractionEnemy);
            }
            else if (target.HasNPC)
            {
                Player.UpcomingInteractionState = typeof(PlayerStateInteractionNPC);
            }
            else if (target.HasBuilding)
            {
                Player.UpcomingInteractionState = typeof(PlayerStateInteractionBuilding);
            }
            else if (target.HasProp)
            {
                Player.UpcomingInteractionState = typeof(PlayerStateInteractionProp);
            }
            else
            {
                Player.InteractionTarget = null;
                Debug.Log("Player got desynced somehow!");
            }

            Debug.Log("Selected next phase: " + Player.UpcomingInteractionState);
        }
コード例 #32
0
ファイル: HexMap.cs プロジェクト: Niller/TurnBasedRPGEngine
    void CreateNode(int x, int z, int i)
    {
        Vector3 position;
        position.x = (x + z * 0.5f - z / 2) * InnerRadius * 2f;
        position.y = 0f;
        position.z = z * outerRadius * 1.5f;

        HexNode node = nodes [i] = new HexNode ();
        node.Init (position, new Vector3(x,0,z));
    }
コード例 #33
0
ファイル: HexMesh.cs プロジェクト: Niller/TurnBasedRPGEngine
 void Triangulate(HexNode cell)
 {
     Vector3 center = cell.position;
     for (int i = 0; i < 6; i++)
     {
         AddTriangle(
             center,
             center + cell.corners[i],
             center + cell.corners[i+1]
         );
     }
 }
コード例 #34
0
    //STATIC
    //RAYCAST ON TILE LAYER AND RETURN THE TILE THAT WAS HIT, NULL IF NONE WAS HIT
    public static bool TileRaycast(Vector3 origin, Vector3 direction, out HexNode tInfo, LayerMask layer)
    {
        RaycastHit hit;
        if (Physics.Raycast(origin, direction, out hit, Mathf.Infinity, layer)) {

            tInfo = hit.collider.gameObject.GetComponent<HexNode>();
            return true;
        }

        tInfo = null;
        return false;
    }
コード例 #35
0
ファイル: HexNode.cs プロジェクト: hschneidman/NewCatan
	public void addHexNbr(int location){
		int x = this.coords.x;
		int y = this.coords.y;
		if(location!=3 && location!=0){
			if(location<3){ x++;}
			else{ x--;}
		}
		if(location!=1 && location!=4){
			if(location<4 && location >1){ y--;}
			else{ y++;}
        }
        HexNbrs[location] = new HexNode();
		if(!HexNbrs[location].initCoords(x,y)){
			HexNbrs[location] = NodeHolder.instance().HexList[new Point(x,y)];
		}
		HexNbrs[location].HexNbrs[(location+3)%6] = this;
    }
コード例 #36
0
ファイル: HexMesh.cs プロジェクト: Niller/TurnBasedRPGEngine
    public void Triangulate(HexNode[] cells)
    {
        GetComponent<MeshFilter>().mesh = hexMesh = new Mesh();
        hexMesh.name = "Hex Mesh";
        vertices = new List<Vector3>();
        triangles = new List<int>();

        hexMesh.Clear();
        vertices.Clear();
        triangles.Clear();
        for (int i = 0; i < cells.Length; i++)
        {
            Triangulate(cells[i]);
        }
        hexMesh.vertices = vertices.ToArray();
        hexMesh.triangles = triangles.ToArray();
        hexMesh.RecalculateNormals();
    }
コード例 #37
0
    /*
    public Vector3 SetDesiredDirec(Vector3 position) {
        //desiredDirec = direc.normalized;
        desiredDirecEndpoint = position;
        return desiredDirec;
    }
    */
    /// <summary>
    /// Move the Agent in the directoin formed by the line from the star to the end. Returns true when Agent reaches end
    /// </summary>
    /// <param name="start"></param>
    /// <param name="end"></param>
    /// <returns></returns>
    protected bool MoveToLocation(HexNode start, HexNode end)
    {
        //transform.position = Vector3.MoveTowards(transform.position, end.transform.position, moveSpeed * Time.deltaTime);

        Debug.DrawRay(transform.position, desiredDirec, JBirdEngine.MoreColors.orange);

        //SetDesiredDirec(Vector3.Normalize(end.transform.position - transform.position));

        transform.position = MoveToLocationMethod(transform.position,
                                                  desiredPoint,//HACK: start using _trueDirec
                                                  moveSpeed * Time.deltaTime);

        //update current tile to the one the Agent is currently over
        if (Vector3.Distance(transform.position, start.transform.position) > Vector3.Distance(transform.position, end.transform.position)) {
            end.entityOnTile = BattleManager.singleton.selectedAgent;
            start.entityOnTile = null;

            currentTile = end;
        }

        if (transform.position == end.transform.position) {
            //Debug.Log("at location");
            tilesMoved++;
            return true;
        }

        return false;
    }
コード例 #38
0
    public void SetHoveredTile(HexNode tile)
    {
        if (!currentBattleState.canHoverGrid) {//we can't hover over a tile in this state, prevent it from happening
            if (hoveredTile != null) {//clean up any hovered tile if we need to
                hoveredTile.SetNormalMat();
                hoveredTile = null;
            }
            return;
        }

        if (hoveredTile != tile) {//swap out the currently hovered tile
            if (hoveredTile != null) {
                hoveredTile.SetNormalMat();
            }

            hoveredTile = tile;//set parameters of hovered tile
            hoveredTile.SetHoverMat();
        }
    }
コード例 #39
0
 public void ClearFrameInfo()
 {
     selectedTile = null;
     targetTile = null;
     selectedAgent = null;
     selectedAction = null;
 }