Beispiel #1
0
        public override void Execute(IAIContext context)
        {
            AIContext ctx    = (AIContext)context;
            Enemy     entity = (Enemy)ctx.entity;
            Entity    target = ctx.target;

            if (ctx.target != null && ctx.pathTarget != ctx.target && entity.IsGrounded && !entity.IsRagdolled)
            {
                float entityRadius = includeRadius ? entity.Radius : 0;
                float targetRadius = includeTargetRadius ? ctx.target.Radius : 0;
                float distance     = Vector3.Distance(ctx.target.transform.position, entity.transform.position) - entityRadius - targetRadius;

                if (ensureMaxRange)
                {
                    Vector3 direction         = Vector3.Normalize(ctx.target.transform.position - entity.transform.position);
                    float   distanceFromRange = distance - entity.Stats.AttackRange + 0.1f;
                    Vector3 position          = (direction * distanceFromRange) + entity.transform.position;
                    entity.MoveToPosition(position);
                }
                else
                {
                    Vector3 direction = Util.Utilities.Direction(target.transform.position, entity.transform.position);
                    Vector3 position  = (direction * (entityRadius + targetRadius)) + target.transform.position;
                    entity.MoveToPosition(position);
                }
            }
        }
Beispiel #2
0
    public override void Execute(IAIContext context)
    {
        var c = (MainContext)context;

        c.agent.stoppingDistance = 0;
        c.agent.destination      = c.targetPosition;
    }
    public override float Score(IAIContext _context)
    {
        TargetContext context = (TargetContext)_context;

        //var targets = context._surroundingHexCells;
        return(score = 100f / context.oil);
    }
Beispiel #4
0
        public override Qualifier Select(IAIContext context)
        {
            Qualifier bestQualifier = defaultQualifier;
            float     bestScore     = defaultQualifier != null?defaultQualifier.Score(context) : float.MinValue;

            for (int i = 0; i < qualifiers.Count; ++i)
            {
                var qualifier = qualifiers[i];
                var score     = qualifier.Score(context);

                if (score > bestScore)
                {
                    bestScore     = score;
                    bestQualifier = qualifier;
                }
            }

            if (AIDebuggingHook.debugger != null)
            {
                AIDebuggingHook.debugger.BestQualifier(bestQualifier, this);
            }

            if (bestQualifier == null || bestScore < minScoreThreshold)
            {
                return(null);
            }

            return(bestQualifier.Select(context));
        }
Beispiel #5
0
        public override float Score(IAIContext context)
        {
            var c            = (AIContext)context;
            var attackTarget = c.attackTarget;

            if (attackTarget == null)
            {
                // there is not attack target
                return(0f);
            }

            // get the right range
            var range = this.range;

            if (this.useScanRadius)
            {
                range = c.unit.scanRadius;
            }
            else if (this.useAttackRadius)
            {
                range = c.unit.attackRadius;
            }

            var distanceSqr = (c.position - attackTarget.transform.position).sqrMagnitude;

            if (distanceSqr < (range * range))
            {
                // attack target is within range
                return(this.not ? 0f : this.score);
            }

            return(this.not ? this.score : 0f);
        }
Beispiel #6
0
        protected override void Execute(IAIContext context)
        {
            var     c = (AIContext)context;
            Vector3 bestDestination = GetBest(c, c.tacticalPositions);

            //  Move to the best position...
            if (Mathf.Abs(bestDestination.sqrMagnitude) < 0f)
            {
                Debug.Log("Did not get a best destination");
                //EndAction();
                return;
            }


            if (Mathf.Abs(bestDestination.sqrMagnitude) > Mathf.Abs(c.entity.transform.position.sqrMagnitude))
            {
                Debug.Log(string.Format("Entity position:  <{0}>  |  Entity sqrMagnitude:  {1}\nBestDestination position:  <{2}>  |  BestDestination sqrMagnitude:  {3}",
                                        c.entity.transform.position, Mathf.Abs(c.entity.transform.position.sqrMagnitude), bestDestination, Mathf.Abs(bestDestination.sqrMagnitude)));

                c.entity.MoveTo(bestDestination);
                //MoveTo(c.agent, bestDestination);
            }
            else
            {
                //Debug.Log(string.Format("Entity position:  {0}\nBest Destination: {1}", c.entity.transform.position, bestDestination));
                return;
            }
        }
        public float Score(IAIContext context)
        {
            var c     = (ControllerContext)context;
            var nest  = c.controller.nest;
            var count = 0;

            switch (this.unitType)
            {
            case UnitType.Harvester:
            {
                count = nest.harvesterCount;
                break;
            }

            case UnitType.Warrior:
            {
                count = nest.warriorCount;
                break;
            }

            case UnitType.Blaster:
            {
                count = nest.blasterCount;
                break;
            }

            default:
            {
                Debug.LogWarning(this.ToString() + " Unsupported unit type => " + this.unitType);
                break;
            }
            }

            return(Mathf.Max(0f, this.maxScore - count));
        }
        /// <summary>
        /// For Debugging
        /// </summary>
        public Dictionary <IQualifier, float> GetSelectorResults(IAIContext context, IList <IQualifier> qualifiers, IDefaultQualifier defaultQualifer)
        {
            if (selectorResults == null)
            {
                selectorResults = new Dictionary <IQualifier, float>();
            }
            else
            {
                selectorResults.Clear();
            }

            for (int index = 0; index < qualifiers.Count; index++)
            {
                CompositeQualifier qualifier = qualifiers[index] as CompositeQualifier;
                var score = qualifier.Score(context, qualifier.scorers);
                selectorResults.Add(qualifier, score);
            }


            var dq = defaultQualifer as IQualifier;

            selectorResults.Add(dq, defaultQualifer.Score(context));

            return(selectorResults);
        }
Beispiel #9
0
        public float range = 10f;  //  entites within this range


        public override float Score(IAIContext context)
        {
            var c = (AIContext)context;

            //var _score = score;
            //_score += UnityEngine.Random.Range(-score / 10 , score / 10);


            var hostileEntities = c.hostileEntities;

            var count = hostileEntities.Count;

            for (int i = 0; i < count; i++)
            {
                var enemy   = hostileEntities[i];
                var sqrDist = (enemy.position - c.entity.transform.position).sqrMagnitude;

                //  If enemy is within range.
                if (sqrDist <= range * range)
                {
                    return(score);
                }
            }

            return(0f);
        }
Beispiel #10
0
    public override float Score(IAIContext context, HexInfo option)
    {
        var c = (CityContext)context;

        this.score = Weight * option.water * (Threshhold / c.water);
        return(this.score);
    }
Beispiel #11
0
        public override void Execute(IAIContext context)
        {
            // Sets the entity's move target to null
            var c = (AIContext)context;

            c.entity.moveTarget = null;
        }
Beispiel #12
0
    public override void Execute(IAIContext context)
    {
        var c = (SpawnersContext)context;

        m_OffsetX = Random.Range(0f, 9999f);
        m_OffsetY = Random.Range(0f, 9999f);
        for (int x = -250; x < width; x += 10)
        {
            for (int z = -250; z < height; z += 10)
            {
                if (m_SpawnedItems < c.treesOnLevel && CalculateHeight(x, z) >= m_TrashHold)
                {
                    m_SpawnedItems++;
                    NavMesh.SamplePosition(new Vector3(x, c.terrainData.GetHeight(x, z), z), out hit, offset,
                                           NavMesh.AllAreas);
                    if (PhotonNetwork.IsConnected)
                    {
                        PhotonNetwork.Instantiate(selectItemToSpawn(c), hit.position, Quaternion.identity);
                    }
                    else
                    {
                        GameObject.Instantiate((GameObject)Resources.Load(selectItemToSpawn(c)), hit.position,
                                               Quaternion.identity); //todo сделать, чтобы предметы 'лежали' на меше с помощью нормалей
                    }
                }
            }
        }
    }
Beispiel #13
0
        public override float Score(IAIContext context)
        {
            var c    = (AIContext)context;
            var unit = c.unit;

            var observations = unit.observations;
            var count        = observations.Count;

            if (count == 0)
            {
                // unit has no observations
                return(0f);
            }

            for (int i = 0; i < count; i++)
            {
                var obs      = observations[i];
                var resource = obs.GetComponent <ResourceComponent>();
                if (resource == null)
                {
                    // observation is not a resource
                    continue;
                }

                // at least one observed object is a resource component
                return(this.not ? 0f : this.score);
            }

            return(this.not ? this.score : 0f);
        }
Beispiel #14
0
        protected override void DrawGizmos(IAIContext context)
        {
            NavMeshAgent agent     = GetComponent <NavMeshAgent>();
            AIContext    aiContext = context as AIContext;
            var          entity    = aiContext.entity;
            //NavMeshPath path = entity.aiSteer.path;
            NavMeshPath path = entity.aiSteer.agent.path;

            float distSqr = (aiContext.destination - entity.transform.position).sqrMagnitude;


            if (aiContext.destination != Vector3.zero || distSqr > drawRange * drawRange)
            {
                Vector3 height = Vector3.up * yOffset;

                if (path != null)
                {
                    Vector3[] corners = path.corners;
                    for (int c = 0; c < corners.Length - 1; c++)
                    {
                        //distance += Mathf.Abs((corners[c] - corners[c + 1]).magnitude);
                        Handles.color = routeColor;
                        Handles.DrawLine(corners[c] + height, corners[c + 1] + height);
                    }
                }


                Handles.color = waypointColor;
                Handles.DrawSolidDisc(aiContext.destination + height, height, locationRadius);
                //  Stopping distance
                Handles.color = new Color(1, 1, 1, 0.25f);;
                Handles.DrawSolidDisc(aiContext.destination + height, height, entity.aiSteer.arrivalDistance);
            }
        }
Beispiel #15
0
        public override IQualifier Select(IAIContext context, IList <IQualifier> qualifiers, IDefaultQualifier defaultQualifier)
        {
            IQualifier qualifier = defaultQualifier;

            for (int i = 0; i < qualifiers.Count; i++)
            {
                IQualifier item = qualifiers[i];
                if (!item.isDisabled)
                {
                    float single = item.Score(context);
                    if (this._decomposition == DecompositionType.One && single > 0f)
                    {
                        return(item);
                    }
                    if (this._decomposition == DecompositionType.All && single <= 0f)
                    {
                        return(base.defaultQualifier);
                    }
                    qualifier = item;
                    IConnectorAction connectorAction = item.action as IConnectorAction;
                    if (connectorAction != null)
                    {
                        connectorAction.Select(context);
                    }
                }
            }
            if (this._decomposition == DecompositionType.All)
            {
                return(qualifier);
            }
            return(defaultQualifier);
        }
        public override float Score(IAIContext context, IEntity entity)
        {
            // Get the entity's current health scaled with the desired multiplier
            var val = entity.currentHealth * this.multiplier;

            return(this.reversed ? -val : val);
        }
Beispiel #17
0
        public override float Score(IAIContext context, ICanDie option)
        {
            var c        = (AIContext)context;
            var distance = (c.position - option.transform.position).magnitude * this.distanceFactor;

            return(Mathf.Max(0f, this.maxScore - distance));
        }
Beispiel #18
0
        public override IQualifier Select(IAIContext context, List <IQualifier> qualifiers, IDefaultQualifier defaultQualifier)  //  Need default qualifier.  Final return value should be default Qualifier.
        {
            List <IQualifier> qList = new List <IQualifier>(qualifiers);

            if (qList.Count == 0)
            {
                return(defaultQualifier as IQualifier);
            }

            //  Get score for all qualifiers
            for (int index = 0; index < qList.Count; index++)
            {
                CompositeQualifier q = qList[index] as CompositeQualifier;
                var score            = q.Score(context, q.scorers);
            }

            //  Sort list of qualifiers.
            qList.Sort();    //  Sorts in accending order.
            qList.Reverse(); //  Sorts in decending order.
            var best = qList[0];



            //DebugSelectorWinner(context, qList);
            return(best);
        }
        /// <summary>
        /// Gets the best option, i.e. the option that was given the highest combined score by the <see cref="scorers"/>.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="options">The options from which to find the best.</param>
        /// <returns>The best option.</returns>
        public TOption GetBest(IAIContext context, IList <TOption> options)
        {
            TOption best     = default(TOption);
            float   maxScore = float.MinValue;

            var ocount = options.Count;

            for (int i = 0; i < ocount; i++)
            {
                var option = options[i];

                float accumulator = 0f;
                var   scount      = _scorers.Count;
                for (int j = 0; j < scount; j++)
                {
                    var scorer = _scorers[j];
                    if (scorer.isDisabled)
                    {
                        continue;
                    }

                    accumulator += scorer.Score(context, option);
                }

                if (accumulator > maxScore)
                {
                    best     = option;
                    maxScore = accumulator;
                }
            }

            return(best);
        }
Beispiel #20
0
        public override IQualifier Select(IAIContext context, IList <IQualifier> qualifiers, IDefaultQualifier defaultQualifier)
        {
            int        count     = qualifiers.Count;
            float      single    = defaultQualifier.score;
            IQualifier qualifier = null;

            for (int i = 0; i < count; i++)
            {
                IQualifier item = qualifiers[i];
                if (!item.isDisabled)
                {
                    float single1 = item.Score(context);
                    if (single1 > single)
                    {
                        single    = single1;
                        qualifier = item;
                    }
                }
            }
            if (qualifier == null)
            {
                return(defaultQualifier);
            }
            return(qualifier);
        }
Beispiel #21
0
        public override float Score(IAIContext context)
        {
            AIContext ctx   = (AIContext)context;
            float     score = ctx.attention * multiplier;

            return(score);
        }
Beispiel #22
0
 protected override void Execute(IAIContext context)
 {
     for (int i = 0; i < actions.Count; i++)
     {
         actions[i].ExecuteAction(context);
     }
 }
Beispiel #23
0
        public override void Execute(IAIContext context)
        {
            // sets the entity's attack target to null
            var c = (AIContext)context;

            c.entity.attackTarget = null;
        }
Beispiel #24
0
        public override float Score(IAIContext context)
        {
            AIContext ctx    = (AIContext)context;
            Entity    entity = ctx.entity;
            Entity    target = ctx.target;

            float distance = Vector3.Distance(ctx.target.transform.position, entity.transform.position)
                             - (includeRadius ? entity.Radius : 0)
                             - (includeTargetRadius ? ctx.target.Radius : 0);

            if (distance <= entity.Stats.AttackRange)
            {
                bool cone = false;
                bool los  = false;
                if (coneCheck)
                {
                    Vector2 start     = new Vector2(entity.EyePosition.x, entity.EyePosition.z);
                    Vector2 direction = new Vector2(entity.transform.forward.x, entity.transform.forward.z);
                    Vector2 end       = new Vector2(target.EyePosition.x, target.EyePosition.z);
                    cone = Util.Utilities.IsPositionInCone(start, direction, end, entity.Stats.AttackAngle / 2);
                }
                if (losCheck)
                {
                    los = !Physics.Raycast(entity.EyePosition, Util.Utilities.Direction(entity.EyePosition, target.EyePosition), Vector3.Distance(entity.EyePosition, target.EyePosition), losBlock);
                }
                if ((coneCheck ? cone : true) && (losCheck ? los : true))
                {
                    return(not ? 0 : score);
                }
            }
            return(not ? score : 0);
        }
        public float samplingDensity = 4f;      //  The bigger the number, the less sampling points



        protected override void Execute(IAIContext context)
        {
            //Debug.Log(string.Format("Executing action:  {0}", this.GetType().Name));
            //Debug.Log(string.Format("Updating {0}", this.GetType().Name));

            var c      = (AIContext)context;
            var player = c.entity;


            c.tacticalPositions.Clear();

            var halfSamplingRange = this.samplingRange * 0.5f;

            var pos = player.transform.position;

            //  Nested loop in x and z directions.  Starting at negative half sampling range and ending at positinve half sampling range, thus sampling in a square around the entity
            for (var x = -halfSamplingRange; x < halfSamplingRange; x += this.samplingDensity)
            {
                for (var z = -halfSamplingRange; z < halfSamplingRange; z += this.samplingDensity)
                {
                    var p = new Vector3(pos.x + x, 0f, pos.z + z);

                    //  Sample position in the navigation mesh to ensure that the desired position is actually walkable.
                    NavMeshHit hit;
                    if (NavMesh.SamplePosition(p, out hit, this.samplingDensity * 0.5f, NavMesh.AllAreas))
                    {
                        c.tacticalPositions.Add(hit.position);
                    }
                }
            }


            //EndAction();
        }
        protected override void Execute(IAIContext context)
        {
            //Debug.Log(string.Format("Executing action:  {0}", this.GetType().Name));

            var c      = (AIContext)context;
            var entity = c.entity;


            //  Scan for hostileEntities
            c.hostileEntities.Clear();

            // Use OverlapSphere for getting all relevant colliders within scan range, filtered by the scanning layer
            var colliders = Physics.OverlapSphere(entity.transform.position, scanRange, c.entitiesLayer);

            foreach (Collider col in colliders)
            {
                if (col.transform.CompareTag(entityTag))
                {
                    var enemy = col.GetComponent <DummyEntity>();
                    c.hostileEntities.Add(enemy.transform);
                }
            }



            //EndAction();
        }
Beispiel #27
0
        public TOption GetBest(IAIContext context, IList <TOption> options)
        {
            TOption tOption = default(TOption);
            float   single  = Single.MinValue;
            int     count   = options.Count;

            for (int i = 0; i < count; i++)
            {
                TOption item    = options[i];
                float   single1 = 0f;
                int     num     = this._scorers.Count;
                for (int j = 0; j < num; j++)
                {
                    IOptionScorer <TOption> optionScorer = this._scorers[j];
                    if (!optionScorer.isDisabled)
                    {
                        single1 += optionScorer.Score(context, item);
                    }
                }
                if (single1 > single)
                {
                    tOption = item;
                    single  = single1;
                }
            }
            return(tOption);
        }
Beispiel #28
0
        public override float Score(IAIContext context, IEntity attackTarget)
        {
            // calculate the average damage (average between maximum and minimum damage) and scale by the set multiplier
            var val = ((attackTarget.minDamage + attackTarget.maxDamage) * 0.5f) * this.multiplier;

            return(this.reversed ? -val : val);
        }
Beispiel #29
0
        /// <summary>
        /// Calculates a score using the supplied scorers given the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="scorers">The scorers.</param>
        /// <returns>
        /// The score.
        /// </returns>
        public sealed override float Score(IAIContext context, IList <IContextualScorer> scorers)
        {
            float sum = 0f;

            int scorersCount = scorers.Count;

            for (int i = 0; i < scorersCount; i++)
            {
                var scorer = scorers[i];
                if (scorer.isDisabled)
                {
                    continue;
                }

                var score = scorer.Score(context);
                if (score <= this.threshold)
                {
                    return(0f);
                }

                sum += score;
            }

            return(sum);
        }
        public override float Score(IAIContext context, ICanDie option)
        {
            // low health options score closer to MaxScore than options with more health
            var health = option.currentHealth * this.factor;

            return(Mathf.Max(0f, this.maxScore - health));
        }