public async static void DeleteBarrier(Context context, params PendingIntent[] pendingIntents)
        {
            string MethodName = "UpdateBarriers";

            BarrierUpdateRequest.Builder builder = new BarrierUpdateRequest.Builder();
            foreach (PendingIntent pendingIntent in pendingIntents)
            {
                builder.DeleteBarrier(pendingIntent);
            }
            var barrierTask = Awareness.GetBarrierClient(context).UpdateBarriersAsync(builder.Build());

            try
            {
                await barrierTask;

                if (barrierTask.IsCompleted)
                {
                    string logMessage = "Delete barrier success";
                    ShowToast(context, logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    string logMessage = "Delete barrier failed";
                    ShowToast(context, logMessage);
                    Log.Error(MethodName, logMessage, barrierTask.Exception);
                }
            }
            catch (Exception ex)
            {
                string logMessage = "Delete barrier failed";
                ShowToast(context, logMessage);
                Log.Error(MethodName, logMessage, ex);
            }
        }
        public async static void BatchBarrier(Context context, BarrierUpdateRequest.Builder builder)
        {
            string MethodName  = "UpdateBarriers";
            var    barrierTask = Awareness.GetBarrierClient(context).UpdateBarriersAsync(builder.Build());

            try
            {
                await barrierTask;

                if (barrierTask.IsCompleted)
                {
                    string logMessage = "Batch barrier success";
                    ShowToast(context, logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    string logMessage = "Batch barrier failed";
                    ShowToast(context, logMessage);
                    Log.Error(MethodName, logMessage, barrierTask.Exception);
                }
            }
            catch (Exception ex)
            {
                string logMessage = "Batch barrier failed";
                ShowToast(context, logMessage);
                Log.Error(MethodName, logMessage, ex);
            }
        }
        public async static void AddBarrier(Context context, string label, AwarenessBarrier barrier, PendingIntent pendingIntent)
        {
            string MethodName = "UpdateBarriers";

            BarrierUpdateRequest.Builder builder = new BarrierUpdateRequest.Builder();
            // When the status of the registered barrier changes, pendingIntent is triggered.
            // label is used to uniquely identify the barrier. You can query a barrier by label and delete it.
            BarrierUpdateRequest request = builder.AddBarrier(label, barrier, pendingIntent).Build();
            var barrierTask = Awareness.GetBarrierClient(context).UpdateBarriersAsync(request);

            try
            {
                await barrierTask;

                if (barrierTask.IsCompleted)
                {
                    string logMessage = "Add barrier success";
                    ShowToast(context, logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    string logMessage = "Add barrier failed";
                    ShowToast(context, logMessage);
                    Log.Error(MethodName, logMessage, barrierTask.Exception);
                }
            }
            catch (Exception ex)
            {
                string logMessage = "Add barrier failed";
                ShowToast(context, logMessage);
                Log.Error(MethodName, logMessage, ex);
            }
        }
Esempio n. 4
0
        private async void QueryDeviceSupportingCapabilities()
        {
            Task <CapabilityResponse> querySupportingCapabilities = Awareness.GetCaptureClient(this).QuerySupportingCapabilitiesAsync();

            try
            {
                await querySupportingCapabilities;
                if (querySupportingCapabilities.IsCompleted && querySupportingCapabilities.Result != null)
                {
                    ICapabilityStatus capabilityStatus = querySupportingCapabilities.Result.CapabilityStatus;
                    int[]             capabilities     = capabilityStatus.GetCapabilities();
                    Log.Info("QueryDeviceSupportingCapabilities", $"capabilities code : {string.Join(" ", capabilities)}");
                    string logMessage = "This device supports the following awareness capabilities:\n";
                    foreach (int capability in capabilities)
                    {
                        logMessage += Constant.GetCapabilityStatus(capability) + "\n";
                    }
                    log.ShowLog(logMessage);
                }
                else
                {
                    Log.Error("QueryDeviceSupportingCapabilities", "Failed to get supported capabilities." + querySupportingCapabilities.Exception);
                    log.ShowLog("Failed to get supported capabilities.");
                }
            }
            catch (System.Exception ex)
            {
                Log.Error("QueryDeviceSupportingCapabilities", "Failed to get supported capabilities." + ex);
                log.ShowLog("Failed to get supported capabilities.");
            }
        }
Esempio n. 5
0
        private void HealingRoutine()
        {
            // Check if already has a healing item
            var item = Me.Inventory.Search(EntityTags.Healing);

            if (item != null)
            {
                // Use the item
                item.Owner.ActivateAction(Me);
            }
            else
            {
                // If has found a healing item already
                if (Focus != null && Focus.TagList.HasTag(EntityTags.Healing))
                {
                    GoTo(Focus.Position);

                    // If in range, pick the item up
                    if (Focus.Interaction.RunInteraction(Me, Interactions.PickUp))
                    {
                        ClearStatus();
                    }
                }
                // If hasn't found a healing item yet
                else
                {
                    Focus = Awareness.FindNearest(EntityTags.Healing);
                }
            }
        }
Esempio n. 6
0
        private async void GetBehaviorStatus(object sender, EventArgs e)
        {
            string MethodName   = "GetBehaviorStatus";
            var    behaviorTask = Awareness.GetCaptureClient(this).GetBehaviorAsync();

            try
            {
                await behaviorTask;
                if (behaviorTask.IsCompleted && behaviorTask.Result != null)
                {
                    BehaviorStatus   behaviorStatus     = behaviorTask.Result.BehaviorStatus;
                    DetectedBehavior mostLikelyBehavior = behaviorStatus.MostLikelyBehavior;
                    string           logMessage         = $"Most likely behavior is {Constant.GetBehavior(mostLikelyBehavior.Type)},the confidence is { mostLikelyBehavior.Confidence}";
                    log.ShowLog(logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    var    exception    = behaviorTask.Exception;
                    string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                    log.ShowLog(errorMessage);
                    Log.Error(MethodName, errorMessage);
                }
            }
            catch (Exception exception)
            {
                string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                log.ShowLog(errorMessage);
                Log.Error(MethodName, errorMessage);
            }
        }
Esempio n. 7
0
    // The CharacterAnimator calls this method, so we will do all of the AI processing within it
    public void UpdateInput(float elapsedTime)
    {
        // By default, have the enemy do nothing
        CharAnimator.CharInput.Horizontal = 0;
        CharAnimator.CharInput.Vertical   = 0;
        CharAnimator.CharInput.Jump       = Vector2.zero;
        CharAnimator.CharInput.Attack     = 0;
        CharAnimator.CharInput.Pickup     = false;

        // Based off the awareness level of the enemy, it'll do 1 of 3 things
        bool awarenessChanged = UpdateAwareness(elapsedTime);

        if (awarenessChanged)
        {
            Awareness.ChangeAwareness();
        }
        switch (Awareness.Level)
        {
        case EnemyAwareness.AwarenessLevel.Unaware:
            if (Settings.ShouldWander)
            {
                Wander(elapsedTime, awarenessChanged);
            }
            break;

        case EnemyAwareness.AwarenessLevel.Searching:
            Search(elapsedTime, awarenessChanged);
            break;

        case EnemyAwareness.AwarenessLevel.Chasing:
            Chase(elapsedTime, awarenessChanged);
            break;
        }
    }
Esempio n. 8
0
        public async Task <IActionResult> PutAwareness([FromRoute] int id, [FromBody] Awareness awareness)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != awareness.AutoId)
            {
                return(BadRequest());
            }

            _context.Entry(awareness).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AwarenessExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 9
0
        private async void GetHeadsetStatus(object sender, EventArgs e)
        {
            string MethodName        = "GetHeadsetStatus";
            var    headsetStatusTask = Awareness.GetCaptureClient(this).GetHeadsetStatusAsync();

            try
            {
                await headsetStatusTask;
                if (headsetStatusTask.IsCompleted && headsetStatusTask.Result != null)
                {
                    IHeadsetStatus headsetStatus = headsetStatusTask.Result.HeadsetStatus;
                    int            status        = headsetStatus.Status;
                    string         logMessage    = $"Headsets are {(status == HeadsetStatus.Connected ? "connected" : "disconnected")}";
                    log.ShowLog(logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    var    exception    = headsetStatusTask.Exception;
                    string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                    log.ShowLog(errorMessage);
                    Log.Error(MethodName, errorMessage);
                }
            }
            catch (Exception exception)
            {
                string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                log.ShowLog(errorMessage);
                Log.Error(MethodName, errorMessage);
            }
        }
Esempio n. 10
0
        private SenseLink EvaluateVision(Signal signal)
        {
            // 1. if it's further than the largest view cone range + 1, don't even bother to process
            Vector3 directionToSignal = calculateDistanceFromSignal(signal);

            if (directionToSignal.magnitude > maxViewConeDistance + 1)
            {
                return(null); // too far to evaluate
            }
            // 2. If it's in range find the maximum awareness for the cones that the signal intersects
            Awareness maxAwarenessForSignal = Awareness.None;
            Awareness temp;

            foreach (ViewCone vc in ViewCones)
            {
                temp = vc.EvaluateSignal(Position, Forward, signal);
                if ((int)temp > (int)maxAwarenessForSignal)
                {
                    maxAwarenessForSignal = temp;
                }
            }

            // 3. If the signal is in a view cone raycast to see if it's visible
            if ((int)maxAwarenessForSignal > (int)Awareness.None)
            {
                Boolean sensed = invokeSelectedLineOfSightAlgorithm(signal);

                if (sensed)
                {
                    return(new SenseLink(Time.time, signal, maxAwarenessForSignal, true, signal.Sense));
                }
            }

            return(null);
        }
Esempio n. 11
0
        private async void GetLightIntensity(object sender, EventArgs e)
        {
            string MethodName       = "GetLightIntensity";
            var    ambientLightTask = Awareness.GetCaptureClient(this).GetLightIntensityAsync();

            try
            {
                await ambientLightTask;
                if (ambientLightTask.IsCompleted && ambientLightTask.Result != null)
                {
                    IAmbientLightStatus ambientLightStatus = ambientLightTask.Result.AmbientLightStatus;
                    string logMessage = $"Light intensity is {ambientLightStatus.LightIntensity} lux";
                    log.ShowLog(logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    var    exception    = ambientLightTask.Exception;
                    string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                    log.ShowLog(errorMessage);
                    Log.Error(MethodName, errorMessage);
                }
            }
            catch (Exception exception)
            {
                string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                log.ShowLog(errorMessage);
                Log.Error(MethodName, errorMessage);
            }
        }
Esempio n. 12
0
        private async void GetTimeCategories(object sender, EventArgs e)
        {
            string MethodName         = "GetTimeCategories";
            var    timeCategoriesTask = Awareness.GetCaptureClient(this).GetTimeCategoriesAsync();

            try
            {
                await timeCategoriesTask;
                if (timeCategoriesTask.IsCompleted && timeCategoriesTask.Result != null)
                {
                    ITimeCategories timeCategories = timeCategoriesTask.Result.TimeCategories;
                    foreach (int timeCode in timeCategories.GetTimeCategories())
                    {
                        log.ShowLog(Constant.GetTimeCategory(timeCode));
                        Log.Info(MethodName, timeCode.ToString());
                    }
                }
                else
                {
                    var    exception    = timeCategoriesTask.Exception;
                    string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                    log.ShowLog(errorMessage);
                    Log.Error(MethodName, errorMessage);
                }
            }
            catch (Exception exception)
            {
                string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                log.ShowLog(errorMessage);
                Log.Error(MethodName, errorMessage);
            }
        }
Esempio n. 13
0
        private async void GetBluetoothStatus(object sender, EventArgs e)
        {
            string MethodName          = "GetBluetoothStatus";
            var    bluetoothStatusTask = Awareness.GetCaptureClient(this).GetBluetoothStatusAsync(BluetoothStatus.DeviceCar);

            try
            {
                await bluetoothStatusTask;
                if (bluetoothStatusTask.IsCompleted && bluetoothStatusTask.Result != null)
                {
                    IBluetoothStatus bluetoothStatus = bluetoothStatusTask.Result.BluetoothStatus;
                    int    status     = bluetoothStatus.Status;
                    string logMessage = $"The Bluetooth car stereo are {(status == BluetoothStatus.Connected ? "connected" : "disconnected")}";
                    log.ShowLog(logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    var    exception    = bluetoothStatusTask.Exception;
                    string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                    log.ShowLog(errorMessage);
                    Log.Error(MethodName, errorMessage);
                }
            }
            catch (Exception exception)
            {
                string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                log.ShowLog(errorMessage);
                Log.Error(MethodName, errorMessage);
            }
        }
Esempio n. 14
0
        static CharmLibrary()
        {
            List <Charm> Charms = Utils.LoadCharms().Charms;

            foreach (Charm c in Charms)
            {
                switch (c.Ability)
                {
                case Ability.Archery: {
                    Archery.Add(c);
                    break;
                }

                case Ability.Athletics: {
                    Athletics.Add(c);
                    break;
                }

                case Ability.Awareness: {
                    Awareness.Add(c);
                    break;
                }

                default: {
                    break;
                }
                }
            }
        }
Esempio n. 15
0
        private async void GetLocation(object sender, EventArgs e)
        {
            string MethodName   = "GetLocation";
            var    locationTask = Awareness.GetCaptureClient(this).GetLocationAsync();

            try
            {
                await locationTask;
                if (locationTask.IsCompleted && locationTask.Result != null)
                {
                    Location location   = locationTask.Result.Location;
                    string   logMessage = $"Longtitude: {location.Longitude},Latitude: {location.Latitude}";
                    log.ShowLog(logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    var    exception    = locationTask.Exception;
                    string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                    log.ShowLog(errorMessage);
                    Log.Error(MethodName, errorMessage);
                }
            }
            catch (Exception exception)
            {
                string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                log.ShowLog(errorMessage);
                Log.Error(MethodName, errorMessage);
            }
        }
Esempio n. 16
0
        private void CombatRoutine()
        {
            // If enough time has passed since the last attack
            // Or the aggressor is dead
            if (WaitForTimer(5) || !Aggressor.IsAlive)
            {
                // Stop and forget
                ClearStatus();
                Stop();
                return;
            }

            // If already has a weapon
            if (Me.EquipmentSlots[0].Equipped != null && Me.EquipmentSlots[0].Equipped.TagList.HasTag(EntityTags.Weapon))
            {
                // Move towards the aggressor
                GoTo(Aggressor.Position);

                // If close enough
                if (Me.DistanceTo(Aggressor) < 1.5f)
                {
                    // Use the weapon
                    Me.ActivateEquipment();
                }

                return;
            }

            // If a weapon was found
            if (Focus != null)
            {
                // Give up if the weapon was picked up by something else
                if (Focus.IsChild)
                {
                    Focus = null;
                    return;
                }

                // Move towards the weapon
                GoTo(Focus.Position);

                // If in range, equip the weapon
                if (Focus.Interaction.RunInteraction(Me, Interactions.Equip))
                {
                    Focus = null;
                }

                return;
            }
            // If no weapon was found yet
            else
            {
                // Look for a nearby weapon
                Focus = Awareness.FindNearest(EntityTags.Weapon);
            }

            // If no weapon can be found, flee
            RunAwayFrom(Aggressor.Position);
        }
Esempio n. 17
0
 public SenseLink(float time, Signal signal, Awareness awareness, bool firstHand, SenseType senseType)
 {
     this.TimeLastSensed = time;
     this.signal         = signal;
     this.awarenessLevel = awareness;
     this.FirstHand      = firstHand;
     this.sense          = senseType;
 }
Esempio n. 18
0
 public ViewCone(ViewCone coneToCopy)
 {
     this.FoVAngle         = coneToCopy.FoVAngle;
     this.Range            = coneToCopy.Range;
     this.HorizontalOffset = coneToCopy.HorizontalOffset;
     this.SceneColor       = coneToCopy.SceneColor;
     this.awarenessLevel   = coneToCopy.awarenessLevel;
 }
Esempio n. 19
0
 // Start is called before the first frame update
 void Start()
 {
     Initialize(); // Initialize the entity object
     awareness = GetComponentInChildren<Awareness>();
     brain = gameObject.AddComponent<Brain>();
     brain.awareness = awareness;
     inventory = gameObject.AddComponent<Inventory>();
 }
Esempio n. 20
0
    public void ReceiveAlert(Transform target)
    {
        if (dispossessTimerActive == false) {
            awarenessLevel = Awareness.Aggressive;
            PerformAggressiveBehavior(target);

            GetComponent<SpriteRenderer>().color = Color.red;
        }
    }
Esempio n. 21
0
        public void ShouldFindContextWithoutExplicitlyAdding()
        {
            locator
            .Register(Awareness.Of(() => locator.GetInstance <ISomeService>()))
            .Register(Given <ISomeService> .Then <SomeService>())
            .Register(Given <ITestInterface> .When <ISomeService>(i => i.SomeMethod()).Then <TestCase1>())
            .Register(Given <ITestInterface> .Then <TestCase2>());

            Assert.IsInstanceOf <TestCase1>(locator.GetInstance <ITestInterface>());
        }
Esempio n. 22
0
    private void AggressionCooldownTimer()
    {
        aggressionCooldownTimerLeft -= Time.deltaTime;

        if (aggressionCooldownTimerLeft <= 0.0f)
        {
            awarenessLevel = Awareness.Unaware;

            aggressionCooldownTimerActive = false;
        }
    }
Esempio n. 23
0
 private string GetLevel(Awareness awareness)
 {
     if (awareness == Awareness.None)
     {
         return("");
     }
     else
     {
         return(awareness.ToString() + " awareness");
     }
 }
Esempio n. 24
0
    public void ReceiveAlert(Transform target)
    {
        if (dispossessTimerActive == false)
        {
            awarenessLevel = Awareness.Aggressive;
            PerformAggressiveBehavior(target);
            //JTR - change waypoint

            GetComponent <SpriteRenderer>().color = Color.red;
        }
    }
Esempio n. 25
0
        public async Task <IActionResult> PostAwareness([FromBody] Awareness awareness)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Awareness.Add(awareness);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetAwareness", new { id = awareness.AutoId }, awareness));
        }
Esempio n. 26
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);
            InitializeButtons();

            log = new Logger(FindViewById <LinearLayout>(Resource.Id.ll_log), FindViewById <ScrollView>(Resource.Id.sv_log), this);

            Awareness.GetBarrierClient(this).EnableUpdateWindow(true);
            QueryDeviceSupportingCapabilities();
            CheckAndRequestPermissions();
        }
 public Action <IServiceLocator> Build()
 {
     return(serviceLocator =>
            serviceLocator
            .Register(Awareness.Of(serviceLocator.GetInstance <HandlerContext>))
            .Register(Given <ServiceBusRoute> .Then <ServiceBusRoute>())
            .Register(Given <IHttpHandler> .When <HandlerContext>(ctx => ctx.Type == null).Then <MvcControllerHandler>())
            .Register(Given <IHttpHandler> .Then <ServiceBusHandler>())
            .Register(Given <ServiceBusRouteHandler> .Then <ServiceBusRouteHandler>())
            .Register <Singleton>(Given <IServiceBus> .Then <ServiceBus>())
            .Register(Given <TypeFinder> .Then <TypeFinder>())
            .Register(Given <HandlerContext> .Then <HandlerContext>())
            .Register(Given <NativeAdapter> .Then <NativeAdapter>()));
 }
Esempio n. 28
0
        private async void GetBeaconStatus(object sender, EventArgs e)
        {
            string MethodName = "GetBeaconStatus";
            string ns         = "sample namespace";
            string type       = "sample type";

            byte[]             content = Encoding.ASCII.GetBytes("sample");
            BeaconStatusFilter filter  = BeaconStatusFilter.Match(ns, type, content);
            var beaconTask             = Awareness.GetCaptureClient(this).GetBeaconStatusAsync(filter);

            try
            {
                await beaconTask;
                if (beaconTask.IsCompleted && beaconTask.Result != null)
                {
                    List <IBeaconStatusBeaconData> beaconDataList = beaconTask.Result.BeaconStatus.BeaconData.ToList();
                    string logMessage = string.Empty;
                    if (beaconDataList != null && beaconDataList.Count != 0)
                    {
                        int i = 1;
                        foreach (IBeaconStatusBeaconData beaconData in beaconDataList)
                        {
                            logMessage += $"Beacon Data {i++}\n";
                            logMessage += $"namespace: {beaconData.Namespace}\n";
                            logMessage += $"type: {beaconData.Type}\n";
                            logMessage += $"content: {BitConverter.ToString(beaconData.GetContent())}\n";
                        }
                    }
                    else
                    {
                        logMessage = "No beacon matches filters nearby.";
                    }
                    log.ShowLog(logMessage);
                    Log.Info(MethodName, logMessage);
                }
                else
                {
                    var    exception    = beaconTask.Exception;
                    string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                    log.ShowLog(errorMessage);
                    Log.Error(MethodName, errorMessage);
                }
            }
            catch (Exception exception)
            {
                string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
                log.ShowLog(errorMessage);
                Log.Error(MethodName, errorMessage);
            }
        }
Esempio n. 29
0
        private void LookForFoodRoutine()
        {
            // If already found food
            if (Focus != null)
            {
                // Give up if the target was picked up by something else
                if (Focus.IsChild)
                {
                    ClearStatus();
                    return;
                }

                // If aware of the food
                if (IsAware)
                {
                    // Wait until the "notice" animation has finished before chasing the food
                    if (WaitForAnimation(AnimNoticeHash))
                    {
                        GoTo(Focus.Position);

                        // If in range, pick the food up
                        if (Focus.Interaction.RunInteraction(Me, Interactions.PickUp))
                        {
                            ClearStatus();
                            ResetTimer();
                            return;
                        }
                    }
                }
                // If not yet aware of the food, play the "notice" animation
                else
                {
                    Me.FlipTo(Focus.Position);
                    PlayAnimation(AnimNoticeHash);
                    IsAware = true;
                }
            }
            // If hasn't found food already
            else
            {
                Stop();

                // Look for food after the grace period has passed
                if (WaitForTimer(0.5f))
                {
                    Focus = Awareness.FindNearest(EntityTags.Food);
                }
            }
        }
Esempio n. 30
0
        public void DecreaseAwareness()
        {
            switch (awarenessLevel)
            {
            case Awareness.Low:
                awarenessLevel = Awareness.None;
                break;

            case Awareness.Medium:
                awarenessLevel = Awareness.Low;
                break;

            case Awareness.High:
                awarenessLevel = Awareness.Medium;
                break;
            }
        }
Esempio n. 31
0
        public void IncreaseAwareness()
        {
            switch (awarenessLevel)
            {
            case Awareness.Low:
                awarenessLevel = Awareness.Medium;
                break;

            case Awareness.Medium:
                awarenessLevel = Awareness.High;
                break;

            case Awareness.High:
                break;
            }
            // When increasing awareness the time also has to be reset to avoid premature cooldown
            TimeLastSensed = Time.time;
        }
Esempio n. 32
0
    protected void FixedUpdate()
    {
        // We don't want to update if the player is possessed.
        if (dispossessTimerActive == false) {

            // Retrieve a list of objects that are in the enemies alarmed zone.
            Collider2D[] inSight = Physics2D.OverlapCircleAll(transform.position, alarmedThreshold);

            // For every object that the enemy has the potential to see...
            foreach (Collider2D seenObject in inSight) {

                // If the player is within the enemy's alarmed zone...
                if (seenObject.gameObject.tag.Equals("Player")) {

                    // Calculate the direction between the enemy and the player.
                    Vector3 direction = (seenObject.transform.position - transform.position).normalized;
                    float angle = CalculateAngle(transform.up, direction);
                    // If the angle between the enemy and the player is within the
                    // enemy's line of sight...

                    SimpleAI2D.Facing facing = GetComponent<SimpleAI2D>().facing;

                    // Yikes...
                    if (((facing == SimpleAI2D.Facing.down) && (angle <= (-90 - sightAngle)) || (angle >= (90 + sightAngle))) ||
                        ((facing == SimpleAI2D.Facing.up) && (angle >= (-90 + sightAngle)) && (angle <= (90 - sightAngle))) ||
                        ((facing == SimpleAI2D.Facing.left) && (angle <= (0 - sightAngle)) && (angle >= (-180 + sightAngle))) ||
                        ((facing == SimpleAI2D.Facing.right) && (angle >= (0 + sightAngle)) && (angle <= (180 - sightAngle)))) {

                        // Make a layer mask to ignore the enemy layer when raycasting.

                        // Bit shift the index of the layer (8) to get a bit mask
                        int layerMask = 1 << 8;

                        // This would cast rays only against colliders in layer 8.
                        // But instead we want to collide against everything except layer 8.
                        // The ~ operator inverts a bitmask.
                        layerMask = ~layerMask;

                        // Check to see if anything is between the enemy and the player.
                        RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, Mathf.Infinity, layerMask);

                        if (debug) {

                            // In alarmed zone, but not yet seen.
                            Color rayColor = Color.blue;

                            if (awarenessLevel == Awareness.Alarmed) {
                                rayColor = Color.yellow;
                            } else if (awarenessLevel == Awareness.Aggressive) {
                                rayColor = Color.red;
                            }

                            Debug.DrawRay(transform.position, direction * hit.distance, rayColor);
                        }

                        // If there is nothing between the enemy and the player...
                        if (hit.collider.gameObject.tag.Equals("Player")) {
                            if (awarenessLevel == Awareness.Unaware) {

                                // Make the enemy alarmed.
                                awarenessLevel = Awareness.Alarmed;
                                alarmedTimerActive = true;

                                PerformAlarmedBehavior(seenObject.transform);
                            } else if (awarenessLevel == Awareness.Aggressive) {
                                PerformAggressiveBehavior(seenObject.transform);
                            }
                        }

                        // Otherwise something interrupted the enemy's line of sight, but
                        // the enemy was merely alarmed.
                        else if (awarenessLevel == Awareness.Alarmed) {

                            // Reset the enemy's level of awareness.
                            awarenessLevel = Awareness.Unaware;
                            alarmedTimerActive = false;
                            alarmedTimerLeft = alarmedStateLength;
                        }

                        // Otherwise something interrupted the enemy's line of sight, but
                        // they are still aggressive. We should start the aggression cooldown.
                        // The enemy should be aggressive but not be in an aggression cooldown.
                        else if (awarenessLevel == Awareness.Aggressive && aggressionCooldownTimerActive == false) {
                            aggressionCooldownTimerActive = true;
                            aggressionCooldownTimerLeft = aggressionCooldownLength;
                        }
                    }
                }
            }
        }
    }
Esempio n. 33
0
    private void AlarmedTimer()
    {
        alarmedTimerLeft -= Time.deltaTime;

        float timeUp = 0.0f;

        // If the player is posessing someone, increase the time left on the timer.
        if (GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerPossession>().possessed != null) {
            timeUp = -5.0f;
        }

        if (alarmedTimerLeft <= timeUp) {
            awarenessLevel = Awareness.Aggressive;

            alarmedTimerActive = false;
        }
    }
Esempio n. 34
0
    private void AggressionCooldownTimer()
    {
        aggressionCooldownTimerLeft -= Time.deltaTime;

        if (aggressionCooldownTimerLeft <= 0.0f) {
            awarenessLevel = Awareness.Unaware;

            aggressionCooldownTimerActive = false;
        }
    }
Esempio n. 35
0
    protected override void OnStart()
    {
        awarenessLevel = Awareness.Unaware;

        alarmedTimerLeft = alarmedStateLength;
        aggressionCooldownTimerLeft = aggressionCooldownLength;

        if (alarmedThreshold < aggressiveThreshold) {
            print ("'alarmedThreshold' should be greater than 'aggressiveThreshold'");
        }

        if (waypoints.Count > 0) {
            currentWaypoint = 0;
        }

        foreach (Transform waypoint in waypoints) {
            waypoint.gameObject.GetComponent<SpriteRenderer>().sprite = null;
        }
    }