Example #1
0
    //计算理想状态价值分布,理想收敛系数gamma = 0.9 [0.9 ~ 0.99]
    //public void CalculateStateValueDistribution(AINode _node, AINode _lastNode)
    //{
    //    float gamma = BlackBord.Gamma;

    //    Debug.LogFormat("node{0}.stateValue =========>> {1}", _node.LocationIndex, _node.StateValue);
    //    foreach (var act in _node.actions)
    //    {
    //        if (_lastNode != null && _lastNode.actions.Contains(act))
    //            continue;

    //        if (n.IsOptimalAction(node))
    //            if (!calOnceList.Contains(act))
    //            {
    //                AINode n = BlackBord.GetNode(act);
    //                calOnceList.Add(_node.LocationIndex);
    //                n.StateValue = _node.Reward + gamma * _node.StateValue;
    //                CalculateStateValueDistribution(n, _node);
    //            }
    //    }

    //    foreach (var act in node.actions)
    //    {
    //        if (!calOnceList.Contains(act))
    //        {
    //            calOnceList.Add(act);
    //            CalculateStateValueDistribution(act);
    //        }
    //    }
    //}

    public void CalculateStateValueDistribution(int _targetIndex)
    {
        float            gamma   = BlackBord.Gamma;
        BetterList <int> allLeft = BlackBord.GetActiveNodeIndexes();

        int sum = BlackBord.GetNodesCount();
        int i   = 0;

        while (allLeft.size > 0)
        {
            int    index = (_targetIndex + i) % sum;
            AINode node  = BlackBord.GetNode(index);

            if (!node.IsActived || node.StateValue == -1)
            {
                i++;
                continue;
            }

            float nextStateValue = node.StateValue == 0 ?
                                   (node.Reward + gamma * node.StateValue) : node.StateValue;
            foreach (var act in node.actions)
            {
                AINode n = BlackBord.GetNode(act);

                float nsv = n.Reward + gamma * nextStateValue;
                if (nsv > n.StateValue && n.Reward < 1)
                {
                    n.StateValue = nsv;
                }
            }
            allLeft.Remove(index);
            i++;
        }
    }
Example #2
0
        protected void ProcessTurnToVelocity(double delta_time, AINode ai_node)
        {
            var physic = ai_node.Entity.Get <PhysicComponent>();

            if (physic.Velocity.LengthSquared <= DistanceEpsilonSquared)
            {
                return;
            }

            var max_torque = 1;
            var target     = physic.Velocity;
            var actual     = ai_node.Base.ForwardRelative;
            var direction  = Vector3d.Cross(actual, target);
            var distance   = 1 - Vector3d.Dot(target, actual) / target.Length / actual.Length;

            if (distance > RotationEpsilon)
            {
                var deceleration     = physic.AngularVelocity.Length;
                var velocity_0       = physic.AngularVelocity.Length;
                var slowing_distance = System.Math.Pow(deceleration, 2) / 2 + velocity_0 * delta_time; // / max_torque * entity.Inertia; // slowing_distance = decelertation^2/2 + velocity_0 * delta_time
                if (distance > slowing_distance)
                {
                    physic.Torque += direction.Normalized() * max_torque;
                }
                else
                {
                    physic.Torque += -1 * physic.AngularVelocity.Normalized() * max_torque;
                }
            }
        }
Example #3
0
 // Use this for initialization
 void Start()
 {
     //nodesToPatrol = GetComponentInParent<AIStateManager>().NodesToPatrol;
     nodeToMoveTowards = GetComponentInParent <AIStateManager>().Home;
     homeNode          = GetComponentInParent <AIStateManager>().Home;
     targetNode        = nodeToMoveTowards;
 }
Example #4
0
    public override AINodeResult Execute(ref AINode lastRunningNode, AIMember aiMember)
    {
        GGAIMember member = aiMember as GGAIMember;

        if (CharManager.Instance == null)
        {
            return(AINodeResult.Failure);
        }

        if (CharManager.Instance.MainChar == null)
        {
            return(AINodeResult.Failure);
        }

        Vector3 playerPos = CharManager.Instance.MainChar.transform.position;
        Vector3 myPos     = member.Self.transform.position;
        Vector3 dir       = playerPos - member.Self.transform.position;

        Bullet b = Object.Instantiate(_b);

        b.transform.position = myPos;

        Vector3 target = playerPos + dir.normalized;

        b.transform.DOMove(target, _range / _speed);

        return(AINodeResult.Success);
    }
Example #5
0
    public override AINodeResult Execute(ref AINode lastRunningNode, AIMember aiMember)
    {
        AGAIMember agMember = aiMember as AGAIMember;

        agMember.TestGameObject.transform.position += _move;
        return(AINodeResult.Success);
    }
Example #6
0
        // Use this for initialization
        private void Start()
        {
            ball = GetComponent <Ball>();
            //Find AI skill level from race manager
            RaceManager raceManager = FindObjectOfType <RaceManager>();

            if (raceManager)
            {
                skillLevel = raceManager.Settings.AISkill;
                switch (skillLevel)
                {
                case AISkillLevel.Retarded:
                    targetPointMaxOffset = 200;
                    break;

                case AISkillLevel.Average:
                    targetPointMaxOffset = 20;
                    break;

                case AISkillLevel.Dank:
                    targetPointMaxOffset = 0f;
                    break;
                }
            }

            //Set initial target
            //Doing this from a RacePlayer, as it's done when changing checkpoints, doesn't work - when RacePlayer's
            //constructor runs, this component has not yet been added to the AI ball yet.
            target = StageReferences.Active.checkpoints[0].FirstAINode;
        }
Example #7
0
    public override AINodeResult Execute(ref AINode lastRunningNode, AIMember aiMember)
    {
        GGAIMember member = aiMember as GGAIMember;

        member.Self.ChangeNav(_nav);
        return(AINodeResult.Success);
    }
Example #8
0
    //just excute current node one time and return
    private IEnumerator ActionNode(AINode <bool> aiNode)
    {
        aiNode.lastNode = lastNodeTmp;

        bool isEnter = aiNode.Enter(this); //if false, AITree will ignore current aiNode and execute to its right child

        //Debug.Log(aiNode.GetType() + " By " + UnitManager.GetInstance().units.IndexOf(aiUnit));
        if (isEnter)
        {
            yield return(StartCoroutine(aiNode.Execute()));

            lastNodeTmp = aiNode;
        }
        //Debug.Log(aiNode.GetType() + " By " + UnitManager.GetInstance().units.IndexOf(aiUnit) + " Complete. aiNode.Data:" + aiNode.Data.ToString());
        // decide how to do the next step
        // if the node places in the last level(it dosen't have any child node)
        // just excute its behaviour and stop
        if (aiNode.Data)
        {
            if (aiNode.RChild != null)
            {
                yield return(StartCoroutine(ActionNode(aiNode.RChild as AINode <bool>)));
            }
        }
        else
        {
            if (aiNode.LChild != null)
            {
                yield return(StartCoroutine(ActionNode(aiNode.LChild as AINode <bool>)));
            }
        }

        yield return(0);
    }
    private void OnDrawGizmos()
    {
        if(startNode.isStartNode != true)
            startNode.isStartNode = true;

        if(startNode == null || endNode == null)
        {
            nodes = new List<AINode>(transform.childCount);

            for(int i = 0; i < nodes.Count; i++)
            {
                nodes[i] = transform.GetChild(i).GetComponent<AINode>();
            }

            startNode = nodes[0];
            endNode = nodes[nodes.Count];
        }

        if (!(road = transform.parent.GetComponent<AIRoad>()))
            Debug.LogError("AILane: " + transform.parent + " / " + gameObject.name + " Cant find an AIRoad component attached to the parent");

        Gizmos.color = Color.green;
        for(int i = 0; i < nodes.Count -1; i++)
        {
            Gizmos.DrawLine(nodes[i].transform.position, nodes[i + 1].transform.position);
        }
    }
Example #10
0
    //just excute current node one time and return
    private IEnumerator ActionNode(AINode <bool> aiNode)
    {
        aiNode.lastNode = lastNodeTmp;

        bool isEnter = aiNode.Enter(this); //if false, AITree will ignore current aiNode and execute to its right child

        if (isEnter)
        {
            yield return(StartCoroutine(aiNode.Execute()));

            lastNodeTmp = aiNode;
        }

        // decide how to do the next step
        // if the node places in the last level(it dosen't have any child node)
        // just excute its behaviour and stop
        if (aiNode.Data)
        {
            if (aiNode.RChild != null)
            {
                yield return(StartCoroutine(ActionNode(aiNode.RChild as AINode <bool>)));
            }
        }
        else
        {
            if (aiNode.LChild != null)
            {
                yield return(StartCoroutine(ActionNode(aiNode.LChild as AINode <bool>)));
            }
        }

        yield return(0);
    }
Example #11
0
    private AINode GenerateEntryPointNode()
    {
        var node = new AINode {
            title      = "Start",
            GUID       = Guid.NewGuid().ToString(),
            AIText     = "Entry Point",
            EntryPoint = true
        };

        //Create and set name of port
        var generatedPort = GeneratePort(node, Direction.Output); // change for multi

        generatedPort.portName = "Next";
        //Add port to node
        node.outputContainer.Add(generatedPort);

        node.capabilities &= ~Capabilities.Movable;
        node.capabilities &= ~Capabilities.Deletable;

        // Mabye not needed?
        //Visual refresh
        node.RefreshExpandedState();
        node.RefreshPorts();


        //
        node.SetPosition(new Rect(500, 300, 100, 150));
        return(node);
    }
Example #12
0
    public AINode CreateAINode(string nodeName, Vector2 position)
    {
        var aiNode = new AINode {
            title  = nodeName,
            AIText = nodeName,
            GUID   = Guid.NewGuid().ToString()
        };

        var inputPort = GeneratePort(aiNode, Direction.Input, Port.Capacity.Multi);

        inputPort.portName = "Input";
        aiNode.inputContainer.Add(inputPort);

        aiNode.styleSheets.Add(Resources.Load <StyleSheet>("Node"));

        var button = new ToolbarButton(() => { AddChoicePort(aiNode); });

        button.text = "";
        aiNode.titleContainer.Add(button);

        var textField = new TextField(string.Empty);

        textField.RegisterValueChangedCallback(evt => {
            aiNode.AIText = evt.newValue;
            aiNode.title  = evt.newValue;
        });
        textField.SetValueWithoutNotify(aiNode.title);
        aiNode.mainContainer.Add(textField);

        aiNode.RefreshExpandedState();
        aiNode.RefreshPorts();
        aiNode.SetPosition(new Rect(position, defaultNodeSize));

        return(aiNode);
    }
Example #13
0
    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "NodeTrigger")
        {
            if (other.GetComponent <AINode>().NextNodeInPath == null)
            {
                pathFollowState = PathFollowState.GoToPreviousNode;
            }
            if (other.GetComponent <AINode>().PreviousNodeInPath == null)
            {
                pathFollowState = PathFollowState.GoToNextNode;
            }
            switch (pathFollowState)
            {
            case PathFollowState.GoToNextNode:
                nodeToMoveTowards = other.GetComponent <AINode>().NextNodeInPath;
                break;

            case PathFollowState.GoToPreviousNode:
                nodeToMoveTowards = other.GetComponent <AINode>().PreviousNodeInPath;
                break;

            default:
                break;
            }
        }
    }
Example #14
0
    public AINpcTrap(string fileName, string bossStr)
    {
        m_baseAI = AINodeManager.CreateBossAI(fileName, bossStr);

//         AIBaseData tmpAIBaseData = GetBaseData("PreAttackTime", AIBaseData.DataType.enTime);
//         tmpAIBaseData = GetBaseData("AttackCount", AIBaseData.DataType.enInt);
    }
Example #15
0
    void DefendStructure()
    {
        root        = aINodeCheckSelfHP;
        root.LChild = aINodeHealSelf;
        root.RChild = aINodeMatesInRange;

        aINodeHealSelf.LChild = aINodeStayRest;
        aINodeHealSelf.RChild = aINodeMoveMedicine;

        aINodeMatesInRange.LChild = aINodeEnemyInRange;
        aINodeMatesInRange.RChild = aINodeCheckMatesHP;

        aINodeEnemyInRange.LChild = aINodeCloseToNearestEnemy;
        aINodeEnemyInRange.RChild = aINodeAttackNearestEnemy;

        aINodeCloseToNearestEnemy.RChild = aINodeMoveAI;

        aINodeAttackNearestEnemy.RChild = aINodeMoveAI;

        aINodeMoveAI.LChild = aINodeAfterSkill;
        aINodeMoveAI.RChild = aINodeChooseSkill;

        aINodeCheckMatesHP.LChild = aINodeHealLowestHPMate;
        aINodeCheckMatesHP.RChild = aINodeEnemyInRange;

        aINodeHealLowestHPMate.LChild = aINodeEnemyInRange;
        aINodeHealLowestHPMate.RChild = aINodeMoveMedicine;

        aINodeMoveMedicine.RChild = aINodeMoveAI;
        aINodeChooseSkill.RChild  = aINodeUseSkill;
        aINodeUseSkill.RChild     = aINodeAfterSkill;

        aINodeAfterSkill.LChild = aINodeDefend;
        aINodeAfterSkill.RChild = aINodeNoDefend;
    }
Example #16
0
    public static AINode LoadFile(string file)
    {
        if (!File.Exists(file))
        {
            //Logger.Debug("File {0} Does not Exists!", file);
        }
        XmlDocument xmlDoc = new XmlDocument();

        try
        {
            xmlDoc.Load(file);
        }
        catch (XmlException e)
        {
            //Logger.Error("Cannot Load File {0}, Exception {1}", file, e);
        }

        if (xmlDoc != null)
        {
            AINode node = new AINode();
            node.setXmlData(xmlDoc.DocumentElement);
            return(node);
        }
        return(null);
    }
Example #17
0
        protected void ProcessArrival(double delta_time, AINode ai_node)
        {
            var physic = ai_node.Entity.Get <PhysicComponent>();

            var max_force = physic.thrust;
            var direction = ai_node.AI.TargetPosition.Value - ai_node.Base.Position - physic.Velocity - physic.Velocity * delta_time;
            var distance  = direction.Length;

            if (distance > DistanceEpsilon)
            {
                var deceleration     = physic.Velocity.Length;
                var velocity_0       = physic.Velocity.Length;
                var slowing_distance = System.Math.Pow(deceleration, 2) / 2 + velocity_0 * delta_time; // / max_force * entity.Mass; // slowing_distance = decelertation^2/2 + velocity_0 * delta_time
                if (distance > slowing_distance)
                {
                    physic.Force += direction / distance * max_force;
                }
                else
                {
                    physic.Force += -1 * physic.Velocity.Normalized() * max_force;
                }
            }
            else
            {
                ai_node.AI.TargetPosition = null;
            }
        }
Example #18
0
 public void Update(AINode <L, V> newParent)
 {
     if (newParent.g + action.Cost < g)
     {
         parent = newParent;
         SetNodeActionDetails();
     }
 }
Example #19
0
        public void OnTriggerEnter(Collider other)
        {
            AINode node = other.GetComponent <AINode>();

            if (node && node == target && target.NextNode)
            {
                Target = target.NextNode;
            }
        }
        /// <summary>
        /// 转化单个xml文件为lua文件
        /// </summary>
        /// <returns>lua文件的路径</returns>
        /// <param name="xmlFile">Xml file.</param>
        public static string ConvertFileFromXMLToLua(string xmlFile)
        {
            string path = xmlFile.Replace("Xml", "Lua").Replace(".xml", ".lua");
            string text = AINode.LoadFile(xmlFile).ToString();

            File.WriteAllText(path, text);

            return(path);
        }
    public void Start()
    {
        enemy    = GameObject.Find("EnemyNode").GetComponent <AINode>();
        source   = GetComponent <AudioSource>();
        _manager = GetComponent <PlayerManager>();
        // _flag.transform.position = new Vector3(spawns[0].position.x, , spawns[0].position.z);

        canSpawn = true;
    }
Example #22
0
        protected void ProcessSteering(double delta_time, AINode ai_node)
        {
            if (null == ai_node.AI.TargetPosition)
            {
                return;
            }

            ProcessArrival(delta_time, ai_node);
            ProcessTurnToVelocity(delta_time, ai_node);
        }
Example #23
0
    protected virtual void Awake()
    {
        var player = GameObject.FindWithTag("Player");
        var companion = GameObject.FindWithTag("Companion");

        _gestureScript = player.GetComponent<GradientBasedGestureScript>();
        _player = player.GetComponentInChildren<AINode>();

        _companionScript = companion.GetComponent<CompanionScript>();
    }
Example #24
0
 public virtual void Deserialize(XmlNode xmlNode)
 {
     Debug.Log("AINode public virtual void Deserialize");
     foreach (XmlNode item in xmlNode)
     {
         AINode aiNode = AINodeManager.CreateNodeByTypeName(((XmlElement)item).GetAttribute("Type"));
         aiNode.Deserialize(item);
         mAINodeList.Add(aiNode);
     }
 }
Example #25
0
    static public AINode CreateNodeByTypeName(string typeName)
    {
        Type   uiNameObj    = Type.GetType(typeName);
        object instanceFunc = System.Activator.CreateInstance(uiNameObj);

        System.Reflection.MethodInfo instance = uiNameObj.GetMethod("GetInstance");
        AINode aiNode = instance.Invoke(instanceFunc, null) as AINode;

        return(aiNode);
    }
Example #26
0
    // To execute this node is to execute all the nodes inside it
    public override void execute(Character body)
    {
        AINode currentNode = this.firstNode;

        while (currentNode != null)
        {
            currentNode.execute(body);
            currentNode = currentNode.getNextNode(body);
        }
    }
Example #27
0
    void CommonStructure()
    {
        root = aINodeEnemyInRange;

        aINodeEnemyInRange.LChild = aINodeCloseToNearestEnemy;
        aINodeEnemyInRange.RChild = aINodeChooseSkill;

        aINodeCloseToNearestEnemy.RChild = aINodeAction;

        aINodeChooseSkill.RChild = aINodeAction;
    }
Example #28
0
    public override AINodeResult Execute(ref AINode lastRunningNode, AIMember aiMember)
    {
        GGAIMember    member = aiMember as GGAIMember;
        CharInterface player = CharManager.Instance.MainChar;

        member.Self.transform.DOMove(player.transform.position, 0.3f).OnComplete(() =>
        {
            player.TakeDamage(_damage);
        });

        return(AINodeResult.Success);
    }
Example #29
0
    public float GetActionReward(int _locationIndex)
    {
        float ar = -1f;
        int   i  = actions.IndexOf(_locationIndex);

        if (i >= 0)
        {
            AINode node = BlackBord.GetNode(i);
            ar = node.Reward;
        }
        return(ar);
    }
Example #30
0
        protected void PickTarget(AINode ai_node)
        {
            if (null != ai_node.AI.TargetPosition)
            {
                return;
            }

            ai_node.AI.TargetPosition = new Vector3d(
                (Random.NextDouble() - 0.5) * 100.0,
                (Random.NextDouble() - 0.5) * 100.0,
                (Random.NextDouble() - 0.5) * 100.0
                );
        }
Example #31
0
    public static AINode CreateBossAI(string filename, string AIStr)
    {
        XmlDocument xml   = new XmlDocument();
        TextAsset   asset = PoolManager.Singleton.LoadWithoutInstantiate <TextAsset>("BossAIXml" + "/" + filename + ".xml");

        xml.LoadXml(asset.text);
        //xml.Load(Application.dataPath + "/Resources/BossAIXml" + "/" + filename + ".xml");
        XmlNode root   = xml.SelectSingleNode(AIStr);
        AINode  aiNode = CreateNodeByTypeName(((XmlElement)root).GetAttribute("Type"));

        aiNode.Deserialize(root);
        return(aiNode);
    }
Example #32
0
    public void think(Character body)
    {
        // clear the flags of what is nearby so that the information we get will still be current
        body.invalidateNeighborData();
        AINode currentNode = this.firstNeuron;

        this.shotError = null;
        while (currentNode != null)
        {
            currentNode.execute(body);
            currentNode = currentNode.getNextNode(body);
        }
        this.shotError = null;
    }
    public AINode MakeIntersection(AINode fromNode)
    {
        AINode toNode = joiningNodes[0];
        AIRoad fromRoad = fromNode.lane.road;

        // Select a random node connected to this junction
        int i = Random.Range(0, startNodes.Count);

        if(startNodes[i].lane.road != fromRoad)
        {
            toNode = startNodes[i];
        } else
        {
            if (i < startNodes.Count - 1)
                toNode = startNodes[i + 1];
            else
                toNode = startNodes[i - 1];
        }

        //if(joiningNodes[i].isStartNode)
        //{
        //    if(joiningNodes[i].lane.road != fromRoad)
        //        toNode = joiningNodes[i];
        //    else
        //    {
        //        if (joiningNodes[i - 1].lane.road != fromRoad)
        //            toNode = joiningNodes[i - 1];
        //        else
        //            toNode = joiningNodes[i + 1];
        //    }
        //}
        //else
        //{
        //    if (joiningNodes[i + 1].isStartNode && joiningNodes[i + 1].lane.road != fromRoad)
        //        toNode = joiningNodes[i + 1];
        //    else if(joiningNodes[i - 1].isStartNode && joiningNodes[i - 1].lane.road != fromRoad)
        //        toNode = joiningNodes[i - 1];
        //}

        return toNode;
    }
Example #34
0
    private void Update()
    {
        if ( aiTargetNode.objectActive )
        {
            if ( _companionWaiting == false &&
                 aiTargetNode.GetAffectingCharacter().waitingAtTarget )
                _companionWaiting = true;

            //  Clicked again, so cancel waiting
            if ( Input.GetMouseButtonDown( 0 ) )
            {
                _oldTarget.ActivateObject( this );
                CursorManager.instance.ChangeCursorStatus( CursorManager.CursorGestureStatus.Normal );
                _companionWaiting = false;
            }
        }
        else
        {
            if ( _mouseOvered )
            {
                var action = aiTargetNode.GetAffectingCharacter().currentAction;

                if ( Input.GetMouseButtonDown( 0 ) &&
                     ( action == Character.CharacterAction.None ||
                       action == Character.CharacterAction.Waiting ) )
                {
                    _oldTarget = aiTargetNode.GetAffectingCharacter().Target;

                    aiTargetNode.ActivateObject( this );
                    CursorManager.instance.ChangeCursor( CursorType.Cancel );
                    CursorManager.instance.ChangeCursorStatus( CursorManager.CursorGestureStatus.Capturing );
                }
            }
        }

        if ( _moving )
        {
            if ( _collidingObjects.Count > 0 )
            {
                padObject.transform.localPosition = Vector3.Slerp( padObject.transform.localPosition,
                                                                   new Vector3( 0, -heightDepression, 0 ),
                                                                   Time.deltaTime * 4.0f );
                if ( Math.Abs( padObject.transform.localPosition.y - -heightDepression ) < Mathf.Epsilon )
                    _moving = false;
            }
            else
            {
                padObject.transform.localPosition = Vector3.Slerp( padObject.transform.localPosition, Vector3.zero,
                                                                   Time.deltaTime * 4.0f );
                if ( Math.Abs( padObject.transform.localPosition.y - 0 ) < Mathf.Epsilon )
                    _moving = false;
            }
        }
    }
Example #35
0
    // Use this for initialization
    void Start()
    {
        // get collider data
        BoxCollider2D boxCollider2D = this.GetComponent<BoxCollider2D>();
        if(boxCollider2D != null)
        {
            colliderOffset = boxCollider2D.offset;
            coliderSize = boxCollider2D.size;
        }

        // get sprite renderer component and sprite
        spriteRenderer = this.GetComponent<SpriteRenderer>();
        if (spriteRenderer != null)
        {
            sprite = spriteRenderer.sprite;
        }

        // get current player tile
        Vector3 vPos = this.transform.position;
        tilesSettings = GameObject.FindObjectOfType(typeof(TilesSettings)) as TilesSettings;
        if (tilesSettings != null)
        {
            float fTileWidthHalf = tilesSettings.TileWidth * 0.5f;
            AINode[] aiNodes = tilesSettings.GetComponentsInChildren<AINode>();
            currentNode = aiNodes.FirstOrDefault(node => Mathf.Abs(node.transform.position.x - vPos.x) <= fTileWidthHalf &&
                                                 Mathf.Abs(node.transform.position.y - vPos.y) <= fTileWidthHalf);
        }
    }
Example #36
0
 private void UpdateCurrentTile(Vector3 vPos)
 {
     float fTileWidthHalf = tilesSettings.TileWidth * 0.5f;
     Vector3 vNodePos = currentNode.transform.position;
     if (vPos.x > vNodePos.x + fTileWidthHalf)
     {
         if (vPos.y > vNodePos.y + fTileWidthHalf)
         {
             currentNode = currentNode.GetNeighbor(eDirection.Up_Right);
         }
         else if (vPos.y < vNodePos.y - fTileWidthHalf)
         {
             currentNode = currentNode.GetNeighbor(eDirection.Down_Right);
         }
         else
         {
             currentNode = currentNode.GetNeighbor(eDirection.Right);
         }
     }
     else if (vPos.x < vNodePos.x - fTileWidthHalf)
     {
         if (vPos.y > vNodePos.y + fTileWidthHalf)
         {
             currentNode = currentNode.GetNeighbor(eDirection.Up_Left);
         }
         else if (vPos.y < vNodePos.y - fTileWidthHalf)
         {
             currentNode = currentNode.GetNeighbor(eDirection.Down_Left);
         }
         else
         {
             currentNode = currentNode.GetNeighbor(eDirection.Left);
         }
     }
     else
     {
         if (vPos.y > vNodePos.y + fTileWidthHalf)
         {
             currentNode = currentNode.GetNeighbor(eDirection.Up);
         }
         else if (vPos.y < vNodePos.y - fTileWidthHalf)
         {
             currentNode = currentNode.GetNeighbor(eDirection.Down);
         }
         else
         {
             // no change
         }
     }
 }
    //private void OnTriggerStay()
    //{
    //    Debug.Log("trigger stay");
    //    flWheel.brakeInput = 1.0f;
    //    frWheel.brakeInput = 1.0f;
    //    rlWheel.brakeInput = 1.0f;
    //    rrWheel.brakeInput = 1.0f;
    //    rlWheel.motorInput = 0.0f;
    //    rrWheel.motorInput = 0.0f;
    //}
    private void JoinNodeNetwork()
    {
        if(!currentNode)
        {
            Debug.Log("No current node! attempting to find one");
            AINode[] sceneNodes = GameObject.FindObjectsOfType<AINode>();
            float closestDistance = 0;
            int closestIndex = 0;
            for(int i = 0; i < sceneNodes.Length; i++)
            {
                if(i == 0)
                {
                    closestDistance = Vector3.Distance(transform.position, sceneNodes[i].transform.position);
                    closestIndex = i;
                } else
                {
                    if(sceneNodes[i].isStartNode)
                    {
                        if(closestDistance > Vector3.Distance(transform.position, sceneNodes[i].transform.position))
                        {
                            closestDistance = Vector3.Distance(transform.position, sceneNodes[i].transform.position);
                            closestIndex = i;
                        }
                    }
                }
            }

            currentNode = sceneNodes[closestIndex];
        }
    }
    private void FixedUpdate()
    {
        // Only drive if we have a node to drive towards
        if(currentNode)
        {
            // Drive if we are not going too fast
            if(rigidbody.velocity.magnitude < desiredSpeed)
            {
                rlWheel.motorInput = 1.0f;
                rrWheel.motorInput = 1.0f;
            }

            // Calculate how much to steer and apply it to the car
            Vector3 targetPoint = new Vector3(currentNode.transform.position.x, transform.position.y, currentNode.transform.position.z);
            Vector3 steerVector = transform.InverseTransformPoint(targetPoint);
            float newSteer = rotateSpeed * (steerVector.x / steerVector.magnitude);
            newSteer = Mathf.Clamp(newSteer, -1, 1);

            //carControl.steerInput = Mathf.Lerp(carControl.steerInput, newSteer, Time.deltaTime);
            carControl.steerInput = newSteer;

            // If we are close to the target node, find the next one
            if(Vector3.Distance(transform.position, currentNode.transform.position) < 2)
            {
                if(currentNode.endNodeJunction)
                {
                    currentNode = currentNode.endNodeJunction.MakeIntersection(currentNode);
                } else
                    currentNode = currentNode.lane.nodes[int.Parse(currentNode.gameObject.name)];
            }
        }

        RaycastHit rayHit = new RaycastHit();
        Vector3 rayPos1 = transform.position + (-transform.right * 0.75f) + transform.up + (transform.forward * frontBumperOffset);
        Vector3 rayPos2 = transform.position + transform.up + (transform.forward * frontBumperOffset);
        Vector3 rayPos3 = transform.position + (transform.right * 0.75f) + transform.up + (transform.forward * frontBumperOffset);

        Debug.DrawLine(rayPos2, currentNode.transform.position, Color.red);

        Debug.DrawLine(rayPos1, rayPos1 + (transform.forward * reactionDistance));
        Debug.DrawLine(rayPos2, rayPos2 + (transform.forward * reactionDistance));
        Debug.DrawLine(rayPos3, rayPos3 + (transform.forward * reactionDistance));
        if (Physics.Raycast(rayPos1, transform.forward, out rayHit, reactionDistance) ||
            Physics.Raycast(rayPos2, transform.forward, out rayHit, reactionDistance) ||
            Physics.Raycast(rayPos3, transform.forward, out rayHit, reactionDistance))
        {
            float hitDistance = Vector3.Distance(rayPos2, rayHit.point);

            //print(Mathf.Clamp(reactionDistance - hitDistance, 0, 1));
            flWheel.brakeInput = Mathf.Clamp01(reactionDistance - hitDistance);
            frWheel.brakeInput = Mathf.Clamp01(reactionDistance - hitDistance);
            rlWheel.brakeInput = Mathf.Clamp01(reactionDistance - hitDistance);
            rrWheel.brakeInput = Mathf.Clamp01(reactionDistance - hitDistance);
        }
        else
        {
            flWheel.brakeInput = 0;
            frWheel.brakeInput = 0;
            rlWheel.brakeInput = 0;
            rrWheel.brakeInput = 0;
        }
    }
Example #39
0
 public void Register(AINode obj)
 {
     controlledObjects.Add(obj);
 }
Example #40
0
 public void SetNeighbor(eDirection dir, AINode aiNode)
 {
     Neighbors[(int)dir] = aiNode;
 }