Esempio n. 1
0
        public async Task <AgentResult> Run(int threads, CancellationToken cancellationToken)
        {
            var flattenedTree = Flatten(_requestTree.Requests);
            var results       = new List <AgentThreadResult>();

            var sw = new Stopwatch();

            sw.Start();

            // flatten the tree and "do the work"
            foreach (var requests in flattenedTree)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                // manage the number of threads with TPL Dataflow
                var throttler = new TransformBlock <IAgentJob, AgentThreadResult>(
                    async job => await job.DoWork().ConfigureAwait(false),
                    new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = threads, CancellationToken = cancellationToken
                }
                    );

                var buffer = new BufferBlock <AgentThreadResult>();
                throttler.LinkTo(buffer);

                var jobSet = requests.Select(r => {
                    return(new HttpClientAgentJob(_client, r));
                });

                foreach (var job in jobSet)
                {
                    throttler.Post(job);
                }

                throttler.Complete();
                await throttler.Completion.ConfigureAwait(false);

                IList <AgentThreadResult> processed;
                buffer.TryReceiveAll(out processed);

                results.AddRange(processed);
            }

            // compile results
            var combinedThreadResult = new CombinedAgentThreadResult(results, sw.Elapsed);
            var statsResult          = new AgentStats(threads);

            statsResult.Process(combinedThreadResult);

            var gradsResult = new AgentRequestGrade(_comparerFactory);

            gradsResult.Process(results);

            return(new AgentResult {
                Stats = statsResult, Grades = gradsResult
            });
        }
Esempio n. 2
0
    /// <summary>
    /// Gets, damages and influences targets within area of effect
    /// </summary>
    private void ApplyAoEEffects(float damageToDo, Transform objectPosition, AreaAbility AoEUsed)
    {
        List <Enemy> enemies = new List <Enemy>();

        //Influence enemies within AoE sphere
        Collider[] cols = Physics.OverlapSphere(objectPosition.position,
                                                AoEUsed.effectRadius); //prefab is scaled down - scale up

        foreach (Collider c in cols)
        {
            if (c.name.Split('(')[0].Equals(AoEUsed.name) || c.tag.Equals(gameObject.tag))
            {
                continue;
            }

            Enemy e = c.GetComponentInParent <Enemy>();
            if (e != null)
            {
                e.Influence(gameObject, Emotion.Anger, statComponent.agro);
            }
            enemies.Add(e);

            AgentStats eS = c.GetComponentInParent <AgentStats>();
            if (eS != null)
            {
                StartCoroutine(eS.DoTDamage(damageToDo, AoEUsed.duration));
            }
        }
    }
Esempio n. 3
0
 public void EnableUI(AgentStats a)
 {
     DefaultState();
     active   = UIACTIVE.Agent;
     agentRef = a;
     agentUI.SetActive(true);
 }
Esempio n. 4
0
    private void Awake()
    {
        _body        = new AgentBody();
        _physics     = new AgentPhysics(transform, GetComponent <Rigidbody2D>(), this);
        _state       = new StateMachine();
        _animation   = new AgentAnimation(this, GetComponent <SkeletonAnimation>());
        _groundcheck = GetComponent <GroundCheck>();
        _stats       = new AgentStats(this);
        _agentSkills = GetComponent <AgentSkills>();
        _health      = GetComponent <AgentHealth>();
        _state.ChangeState(new GroundedState(this));

        if (tag == "Player")
        {
            DeathManager.Player = this;
        }
        else
        {
            if (DeathManager.Enemies == null)
            {
                DeathManager.Enemies = new List <Agent>();
            }
            DeathManager.Enemies.Add(this);
        }
    }
Esempio n. 5
0
    public override void Init()
    {
        base.Init();
        agent       = thisTransform.GetComponent <NavMeshAgent>();
        healthS     = thisTransform.GetComponent <Health>();
        statsS      = thisTransform.GetComponent <AgentStats>();
        audioSource = thisTransform.GetComponent <AudioSource>();

        agent.angularSpeed = turnRatio * 110;

        if (animationObject != null)
        {
            animationH = animationObject.GetComponent <Animation>();

            animationH[run.name].speed  = loopRunAnimSpeed;
            animationH[idle.name].speed = loopIdleAnimSpeed;
            for (int i = 0; i < attackA.Length; i++)
            {
                animationH[attackA[i].name].speed = attackAnimSpeed;
            }
        }

        InitializeStats();

        //Reset(); inte här
    }
Esempio n. 6
0
 void Start()
 {
     iff_channel = GetComponent <IFFTag>().IFF_channel;
     stats       = GetComponent <AgentStats>();
     anim        = GetComponent <Animator>();
     anim.SetInteger("ZombieState", 0);
 }
Esempio n. 7
0
        void HandleNewStats(AgentStats stats)
        {
            Debug.Log("New stats");
            ActionPoints.maxValue     = stats.actionPointsPerTurn;
            ActionPoints.currentValue = stats.actionPoints;

            Health.maxValue     = stats.maxHealth;
            Health.currentValue = stats.health;

            //TODO: Defence doesn't seem to be assigned
            var defenceLevel = stats.defence + 1;

            Defence.maxValue     = defenceLevel;
            Defence.currentValue = defenceLevel;

            Keys.maxValue     = 3;
            Keys.currentValue = stats.keys;

            PlayerName.text = stats.name;
            HandleXPChange(stats.xp);

            //PlayerIcon.image = ??

            HandleNewLevel(Tower.ActiveLevel);
            Showing = true;
        }
Esempio n. 8
0
        private static string GetAsciiHistogram(AgentStats stats)
        {
            if (stats.Histogram.Length == 0)
            {
                return(string.Empty);
            }

            const string filled        = "█";
            const string empty         = " ";
            var          histogramText = new string[7];
            var          max           = stats.Histogram.Max();

            foreach (var t in stats.Histogram)
            {
                for (var j = 0; j < histogramText.Length; j++)
                {
                    histogramText[j] += t > max / histogramText.Length * (histogramText.Length - j - 1) ? filled : empty;
                }
            }

            var text    = "Latency Histogram\r\n\r\n" + string.Join("\r\n", histogramText);
            var minText = string.Format("{0:0.000} ms ", stats.Min);
            var maxText = string.Format(" {0:0.000} ms", stats.Max);

            text += "\r\n" + minText + new string('=', stats.Histogram.Length - minText.Length - maxText.Length) + maxText;
            return(text);
        }
Esempio n. 9
0
        internal static void DrawStatusCodes(AgentStats stats)
        {
            var codes = stats.StatusCodes.OrderByDescending((kv) => kv.Value);

            Console.WriteLine();
            Console.WriteLine("Http Codes");

            int numCodes = 0;

            foreach (var code in codes)
            {
                // return top 3
                if (numCodes >= 3)
                {
                    break;
                }

                Console.WriteLine("    {0}s:           {1}", code.Key, code.Value);
                numCodes++;
            }

            if (codes.Count() > 3)
            {
                var remainingCodes =
                    codes
                    .Skip(3)
                    .Select(kv => kv.Value)
                    .Aggregate((total, next) => total + next);


                Console.WriteLine("    other:           {0}", remainingCodes);
            }
        }
Esempio n. 10
0
        private static string GetAsciiStartTimeSeries(AgentStats stats)
        {
            if (stats.TimeSeries.Length == 0)
            {
                return(string.Empty);
            }

            const string filled     = "█";
            const string empty      = " ";
            var          seriesText = new string[7];
            var          max        = stats.Histogram.Max();

            foreach (var t in stats.TimeSeries)
            {
                for (var j = 0; j < seriesText.Length; j++)
                {
                    seriesText[j] += t > max / seriesText.Length * (seriesText.Length - j - 1) ? filled : empty;
                }
            }

            var text    = "Request Count Over Time\r\n\r\n" + string.Join("\r\n", seriesText);
            var minText = string.Format("{0} ", stats.FirstRequestTime.ToString("MM/dd HH:mm:ss"));
            var maxText = string.Format(" {0}", stats.LastRequestTime.ToString("MM/dd HH:mm:ss"));

            text += "\r\n" + minText + new string('=', stats.TimeSeries.Length - minText.Length - maxText.Length) + maxText;
            return(text);
        }
Esempio n. 11
0
 // Start is called before the first frame update
 void Awake()
 {
     debugTarget = GameObject.Find("DebugTarget");
     path        = new List <Vector3>();
     pathFinder  = GetComponent <Pathfinder>();
     actionTime  = pathUpdateStep;
     stats       = GetComponent <AgentStats>();
 }
Esempio n. 12
0
 private void SetTarget(Transform target)
 {
     if (currentTarget != target)
     {
         currentTarget      = target;
         currentTargetStats = currentTarget.GetComponent <AgentStats>();
         targetEnemy        = target.GetComponent <Enemy>();
     }
 }
Esempio n. 13
0
        AgentStats createMonster(Dictionary <Ability, int> state)
        {
            var stats = new AgentStats();

            stats.maxHealth           = Health[state[Health]].value;
            stats.actionPointsPerTurn = ActionPoints[state[ActionPoints]].value;
            stats.defence             = Defence[state[Defence]].value;
            return(stats);
        }
        public void InitPanel(IBattleAgent agent)
        {
            AgentStats stats = agent.GetStatsInfo();

            agentName.text    = stats.agentName;
            level.text        = "LVL " + stats.level;
            status.text       = "";
            health.text       = stats.healthPoints + "/" + stats.healthPoints;
            agentImage.sprite = agent.GetSprite();
        }
Esempio n. 15
0
    public void MoveCamTo(AgentStats stats)
    {
        _UIManager.targeted   = UIManager.UIACTIVE.Agent;
        _UIManager.agentRef   = stats;
        traversing            = true;
        targetMoves           = true;
        camLookAt             = stats.gameObject.transform.position;
        traversalMovingTarget = stats.gameObject;
        traversalTimePassed   = 0.0f;

        CalcTraversalTarget();
    }
Esempio n. 16
0
        public void CommitStats()
        {
            var stats = new AgentStats();

            stats.actionPointsPerTurn = actionPoints.Value;
            stats.maxHealth           = health.Value;
            stats.defence             = defence.Value;
            if (!upgrading)
            {
                stats.health       = stats.maxHealth;
                stats.actionPoints = stats.actionPointsPerTurn;
                stats.name         = namer.Name;
                Tower.Player.SetStats(stats);
                var weapon1 = Physical.WeaponSmith.Smith(points, true);
                Tower.Player.Weapon.SetStats(weapon1);
                Tower.Player.alive = true;
                Tower.Spawn();
                if (points > 0)
                {
                    WeaponStats weapon2 = WeaponStats.DefaultWeapon;
                    for (int i = 0; i < 5; i++)
                    {
                        weapon2 = Physical.WeaponSmith.Smith(points, true);
                        if (weapon1 != weapon2)
                        {
                            break;
                        }
                    }
                    WeaponSelect.Show(weapon2);
                }
                else
                {
                    Time.timeScale = 1;
                }
            }
            else
            {
                stats.name         = playerStats.name;
                stats.xp           = Mathf.Max(0, instance.points);
                stats.health       = playerStats.health;
                stats.actionPoints = playerStats.actionPoints;
                stats.keys         = playerStats.keys;
                stats.position     = playerStats.position;

                Tower.Player.SetStats(stats);
                Time.timeScale = 1;
            }
            transform.GetChild(0).gameObject.SetActive(false);
            transform.GetChild(1).gameObject.SetActive(false);
        }
Esempio n. 17
0
        private void GetAgentStatsForDay(DateTime curDay)
        {
            SqlCommand    cmd = new SqlCommand(CreateAgentStatQuery(curDay), conn);
            SqlDataReader sdr = cmd.ExecuteReader();

            while (sdr.Read())
            {
                if (sdr[0] != DBNull.Value)
                {
                    AgentStats.Add(new AgentStat(campaign, (long)sdr[0]));
                }
            }
            sdr.Close();
        }
Esempio n. 18
0
 internal static void DrawStats(AgentStats stats)
 {
     Console.WriteLine(StatsResultString,
                       stats.Count,
                       stats.Elapsed.TotalSeconds,
                       stats.RequestsPerSecond,
                       stats.Bandwidth,
                       stats.Errors,
                       stats.Median,
                       stats.StdDev,
                       stats.Min,
                       stats.Max,
                       GetAsciiHistogram(stats),
                       GetAsciiStartTimeSeries(stats));
 }
Esempio n. 19
0
    private float healFXTime = -1f;    //Time before heal after pressed: -1f BECAUSE EFFECT TIME IS INACCURATE - THIS IS TO SYNC THE FX WITH HEALTH INCREASE

    private void Awake()
    {
        statComponent = GetComponent <AgentStats>();
        if (zapSource != null)
        {
            zapTargeter  = zapSource.GetComponentInChildren <particleAttractorLinear>();
            zapParticles = zapSource.GetComponent <ParticleSystem>();
        }

        if (healPrefab != null)
        {
            additionalHealCooldown += healPrefab.GetComponent <ParticleSystem>().main.duration;
            healFXTime             += healPrefab.GetComponent <ParticleSystem>().main.duration;
        }
    }
Esempio n. 20
0
    public void Init(GameObject gameObject, AgentStats agentStats)
    {
        mTransform = transform;
        lastPos    = mTransform.position;

        agent = gameObject.GetComponent <NavMeshAgent>();

        if (agent == null)
        {
            Debug.LogError("No Agent Found!");
        }
        else
        {
            SetSpeed(agentStats.idleSpeed);
        }
    }
Esempio n. 21
0
    public AgentState(GameObject gameObject) : base(gameObject)
    {
        self           = gameObject.GetComponent <Agent>();
        agentStats     = self.agentStats;
        controller     = gameObject.GetComponent <AgentController>();
        groundLayer    = self.groundLayer;
        charController = gameObject.GetComponent <CharacterController>();
        weapons        = gameObject.GetComponent <AgentWeapons>();
        health         = gameObject.GetComponent <AgentHealth>();
        stamina        = gameObject.GetComponent <AgentStamina>();
        vigor          = gameObject.GetComponent <AgentVigor>();
        anim           = gameObject.GetComponentInChildren <Animator>();
        audioManager   = AudioManager.instance;
        poolManager    = PoolManager.Instance;
        animEvents     = gameObject.GetComponentInChildren <AgentAnimEvents>();
        navAgent       = gameObject.GetComponent <NavMeshAgent>();
        audio          = gameObject.GetComponentInChildren <AudioSource>();

        transitionsTo.Add(new Transition(typeof(Dying), IsDead));
        transitionsTo.Add(new Transition(typeof(TakingDamage), () => health.TookSignificatDamage));
    }
Esempio n. 22
0
    // Use this for initialization
    void Start()
    {
        bitePrefab = Resources.Load <GameObject>("Prefabs/Fangs");
        SceneCEO sceo = GameObject.Find("SceneCEO").GetComponent <SceneCEO>();

        for (int i = 0; i < sceo.spawnedManagerList.Count; i++)
        {
            if (sceo.spawnedManagerList[i].GetComponent <SwarmMovementManager>() != null)
            {
                swarmManager = sceo.spawnedManagerList[i].GetComponent <SwarmMovementManager>();
            }
        }

        stats              = (Instantiate(statsFab) as GameObject).GetComponent <AgentStats>();
        curBehavior        = Instantiate(normalBehaviorPrefab);
        lastTimeDirChanged = Time.time - dirChangeDelay + 0.1f; //force update
        curTargetPos       = lastTargetPos = transform.position;
        //Debug.Log(gameObject.name + " start pos " + transform.position + ", curTargetPos=" + curTargetPos + ", lastTargetPos=" + lastTargetPos + ", bMap=" + curBehavior.name);
        //Debug.Log(gameObject.name + " maxMovePerSec=" + stats.maxMoveSpeedPerSec + ", strideDist=" + stride + ", timeBetweenSteps=" + dirChangeDelay);
        firstUpdate = true;
        retardCheck();
    }
Esempio n. 23
0
    private IEnumerator Heal(float amount)
    {
        //Means if we change target, the new target isn't healed when coroutine finishes
        AgentStats tempTarget = currentTargetStats;

        if (tempTarget != null)
        {
            healFinishTime = Time.time + additionalHealCooldown;
            GameObject fx = Instantiate(healPrefab, currentTarget, false);
            fx.transform.position = currentTarget.position;
            fx.transform.parent   = currentTarget;

            yield return(new WaitForSeconds(healFXTime));

            AudioManager.Instance.Play("Heal");
            tempTarget.Heal(amount);

            Destroy(fx);
        }
        else
        {
            Debug.Log("Heal on CD");
        }
    }
Esempio n. 24
0
 public AgentModel(Sprite sprite, PokemonStats statsSource, List <MoveModel> moveSet)
 {
     if (moveSet.Count > 4)
     {
         return;
     }
     this.sprite       = sprite;
     this.statsSource  = statsSource;
     this.moveSet      = moveSet;
     this.currentStats = new AgentStats()
     {
         agentName      = statsSource.pokemonName,
         healthPoints   = statsSource.hp,
         attack         = statsSource.attack,
         defense        = statsSource.defense,
         magic_attack   = statsSource.attack,
         magic_defense  = statsSource.magic_defense,
         speed          = statsSource.speed,
         luck           = statsSource.luck,
         totalExp       = 0,
         expToNextLevel = 25,
         level          = 5
     };
 }
Esempio n. 25
0
        public async Task AgentStats(CommandContext ctx, [RemainingText] string steamIDOrUsername)
        {
            // Find Agents
            List <Agent> agents = await this.agentService.SearchAgent(steamIDOrUsername);

            // Build Base Embed.
            DiscordEmbedBuilder userDetails = new DiscordEmbedBuilder
            {
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"IntruderFPS API",
                },
                Color = new DiscordColor(95, 95, 95),
            };

            // If the count is 0, no agents found with that name/i
            if (agents.Count == 0)
            {
                userDetails.AddField($"No agent found", "Try a different search");
            }

            // more than one agents returned.
            if (agents.Count > 1)
            {
                string extraAgents = string.Empty;
                int    addedAgents = 0;
                foreach (Agent agent in agents)
                {
                    addedAgents++;
                    if (addedAgents > 12)
                    {
                        break;
                    }
                    else
                    {
                        extraAgents += $"{agent.Name} | {agent.SteamID}\n";
                    }
                }

                userDetails.AddField($"Did you mean any of these agents?", extraAgents);
            }

            if (agents.Count == 1)
            {
                Agent agent = agents.FirstOrDefault();

                // See if local DB has agent stored or not.
                if (this.agentService.CheckDBAgent(agent.SteamID))
                {
                    await this.agentService.UpdateDBAgentAsync(agent);
                }
                else
                {
                    // No DB agent found, lets store them.
                    await this.agentService.StoreAgentDBAsync(agent.SteamID);
                }

                AgentStats agentStats = await this.agentService.GetAgentStatsAsync(agent.SteamID);

                userDetails.Url = $"https://intruderfps.com/agents/{agent.SteamID}/";
                float levelProgression = 0;
                float matchWLPercent   = 0;
                float roundsWLPercent  = 0;
                float killDeathPercent = 0;
                try
                {
                    float totalRounds    = agentStats.RoundsWonCapture + agentStats.RoundsWonHack + agentStats.RoundsWonElim + agentStats.RoundsWonTimer + agentStats.RoundsWonCustom + agentStats.RoundsTied;
                    float totalRoundsWon = totalRounds - agentStats.RoundsTied;
                    totalRounds += agentStats.RoundsLost;
                    float totalMatches = agentStats.MatchesWon + agentStats.MatchesLost;
                    matchWLPercent  = agentStats.MatchesWon / totalMatches * 100;
                    roundsWLPercent = totalRoundsWon / totalRounds * 100;
                    float totalKills = agentStats.Kills + agentStats.Deaths;
                    killDeathPercent = agentStats.Kills / (float)agentStats.Deaths;
                    float lvlXpRequired = 0;
                    if (agentStats.LevelXPRequired is null)
                    {
                        lvlXpRequired = 0;
                    }
                    else
                    {
                        lvlXpRequired = (float)agentStats.LevelXPRequired;
                    }

                    levelProgression = (agentStats.LevelXP / (float)lvlXpRequired) * 100;
                }
                catch (DivideByZeroException)
                {
                    Console.WriteLine($"Found a user but had no match or round data | User: {agent.Name} | {agent.SteamID}");
                }

                string lvlProg     = string.Empty;
                double lvlProgress = Math.Floor((double)Math.Round(levelProgression, 0) / 10);

                for (int i = 0; i < (int)lvlProgress; i++)
                {
                    lvlProg += "▰";
                }

                if (float.IsNaN(killDeathPercent))
                {
                    matchWLPercent   = 0;
                    roundsWLPercent  = 0;
                    killDeathPercent = 0;
                }

                userDetails.Footer.Text = $"Matches W/L: {Math.Round(float.IsNaN(matchWLPercent) ? 0 : matchWLPercent, 1)}% | Rounds W/L: {Math.Round(float.IsNaN(roundsWLPercent) ? 0 : roundsWLPercent, 1)}% | K/D: {(float.IsNaN(killDeathPercent) ? "0" : killDeathPercent.ToString("0.00", CultureInfo.CurrentCulture))} | Time Played: {agentStats.TimePlayed / 3600} Hrs";

                userDetails.Thumbnail = new DiscordEmbedBuilder.EmbedThumbnail
                {
                    Url = agent.AvatarURL,
                };

                userDetails.Title = $"{agent.Name}   //   Level: {agentStats.Level}";

                userDetails.Description =
                    $"{agentStats.LevelXP}*xp* `{lvlProg.PadRight(10, '▱')}` {agentStats.LevelXPRequired}*xp* - {Math.Round(levelProgression, 1)}% \n" +
                    $"**Arrests**: `{agentStats.Arrests}` | **Captures**: `{agentStats.Captures}` | **Hacks**: `{agentStats.NetworkHacks}`\n";
            }

            if (ctx.Channel.IsThread || ctx.Channel.IsPrivate)
            {
                await ctx.RespondAsync(embed : userDetails.Build());
            }
            else
            {
                ThreadQueryResult ctxArchivedThreads = await ctx.Channel.ListPublicArchivedThreadsAsync();

                IReadOnlyList <DiscordThreadChannel> publicArchThreads = ctxArchivedThreads.Threads;

                // Check to see if we have archived threads for this user.
                foreach (DiscordThreadChannel thread in publicArchThreads)
                {
                    if (thread.CreatorId == Users.Bloon)
                    {
                        IReadOnlyList <DiscordThreadChannelMember> threadMembers = await thread.ListJoinedMembersAsync();

                        foreach (DiscordThreadChannelMember user in threadMembers)
                        {
                            // User has an open thread for this command.
                            if (user.Id == ctx.User.Id && thread.Name.Contains($"{ctx.Member.DisplayName} -") && thread.ThreadMetadata.IsArchived)
                            {
                                await thread.SendMessageAsync(embed : userDetails.Build());

                                return;
                            }
                        }
                    }
                }

                // Check if we have any public open threads for this user.
                IReadOnlyList <DiscordThreadChannel> publicThreads = ctx.Channel.Threads;
                foreach (DiscordThreadChannel thread in publicThreads)
                {
                    if (thread.CreatorId == Users.Bloon)
                    {
                        IReadOnlyList <DiscordThreadChannelMember> threadMembers = await thread.ListJoinedMembersAsync();

                        foreach (DiscordThreadChannelMember user in threadMembers)
                        {
                            // User has an open thread for this command.
                            if (user.Id == ctx.User.Id && thread.Name.Contains($"{ctx.Member.DisplayName} -") && !thread.ThreadMetadata.IsArchived)
                            {
                                await thread.SendMessageAsync(embed : userDetails.Build());

                                return;
                            }
                        }
                    }
                }

                var mess = await ctx.Message.CreateThreadAsync($"{ctx.Member.DisplayName} - {steamIDOrUsername} Stats", archiveAfter : DSharpPlus.AutoArchiveDuration.Hour, reason : "User ran .stats command");

                await mess.SendMessageAsync(embed : userDetails.Build());

                return;
            }
        }
Esempio n. 26
0
 public override void Initialize()
 {
     stats       = new AgentStats();
     gameManager = GetComponentInParent <GameManagerScript>();
     SetResetParameters();
 }
Esempio n. 27
0
 private void Start()
 {
     stats        = gameObject.GetComponent <Agent>().agentStats;
     CurrentVigor = MaxVigor;
     vigorTimer   = stats.vigorRegenDelay;
 }
Esempio n. 28
0
 private void Start()
 {
     stats          = gameObject.GetComponent <Agent>().agentStats;
     CurrentStamina = MaxStamina;
     staminaTimer   = stats.staminaRegenDelay;
 }
Esempio n. 29
0
    void Shoot()
    {
        RaycastHit hit;

        if (DamageType == AgentStats.DamageType.pistol)
        {
            if (pistolAnimations.shooting || pistolAnimations.reloading)
            {
                Debug.Log("Cannot shoot while shooting or reloading");
                return;
            }

            Collider[] hitColliders = Physics.OverlapSphere(transform.position, pistolNoiseRange);

            foreach (Collider col in hitColliders)
            {
                ZombieController enemy = col.GetComponent <ZombieController>();
                if (enemy != null)
                {
                    enemy.Alert(this.gameObject);
                }
            }

            if (currentPistolMagazine <= 0)
            {
                return;
            }

            audio.Play("PistolShot");
            currentPistolMagazine--;
            pistolAnimations.anim.SetInteger("RoundsLoaded", currentPistolMagazine);
            pistolAnimations.anim.SetTrigger("Fire");


            stats.ammoCounter?.SetAmmoCounter(currentPistolMagazine, stats.pistolAmmo);


            if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, pistolRange, layerMask))
            {
                AgentStats enemyStat = hit.transform.GetComponentInParent <AgentStats>();
                if (enemyStat != null)
                {
                    enemyStat.ApplyDamage(stats.GetDamageValue(DamageType), DamageType, stats);
                }

                GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
                Destroy(impactGO, 2.5f);
            }
        }
        else
        if (DamageType == AgentStats.DamageType.shotgun)
        {
            if (shotgunAnimations.shooting || shotgunAnimations.reloading)
            {
                Debug.Log("Cannot shoot while shooting or reloading");
                return;
            }

            /////////////////////////////Alert Nearby agents////////////////////////////////////////
            Collider[] hitColliders = Physics.OverlapSphere(transform.position, shotgunNoiseRange);

            foreach (Collider col in hitColliders)
            {
                ZombieController enemy = col.GetComponent <ZombieController>();
                if (enemy != null)
                {
                    enemy.Alert(this.gameObject);
                }
            }
            ////////////////////////////////////////////////////////////////////////////////////////

            if (currentShotgunMagazine <= 0)
            {
                return;
            }

            //Start shooting animation
            shotgunAnimations.anim.SetInteger("RoundsLoaded", currentShotgunMagazine);
            shotgunAnimations.anim.SetTrigger("Fire");
            audio.Play("ShotgunShot");
            currentShotgunMagazine--;
            stats.ammoCounter?.SetAmmoCounter(currentShotgunMagazine, stats.shotgunAmmo);
            RaycastHit shotHit;

            for (int i = 0; i < shotgunPellets; i++)
            {
                var v3Offset = transform.up * Random.Range(0.0f, shotgunVariance);
                v3Offset = Quaternion.AngleAxis(Random.Range(0.0f, 360.0f), transform.forward) * v3Offset;
                Vector3 v3Hit = fpsCam.transform.forward * shotgunRange + v3Offset;


                if (Physics.Raycast(fpsCam.transform.position, v3Hit, out shotHit, shotgunRange, layerMask))
                {
                    AgentStats enemyStat = shotHit.transform.GetComponentInParent <AgentStats>();
                    if (enemyStat != null)
                    {
                        enemyStat.ApplyDamage(stats.GetDamageValue(DamageType), DamageType, stats);
                    }
                }

                GameObject impactGO = Instantiate(impactEffect, shotHit.point, Quaternion.LookRotation(shotHit.normal));
                Destroy(impactGO, 2.5f);
            }
        }
        else
        {
            return;
        }
    }
Esempio n. 30
0
 private void Awake()
 {
     agentPathfinding = gameObject.GetComponent <AgentPathfinder>();
     stats            = GetComponent <AgentStats>();
 }