Exemplo n.º 1
0
    public void ChangeToCursor(BlobState _state)
    {
        if (cursorState != _state)
        {
            cursorState = _state;

            switch (_state)
            {
            case BlobState.PASSIVE:
                blobLine.colorGradient = passiveColour;
                wobbleActive           = 1;
                lineWidth = passiveLineWidth;
                break;

            case BlobState.ACTIVE:
                blobLine.colorGradient    = activeColour;
                wobbleActive              = 0;
                blobLine.widthMultiplier *= 2;
                lineWidth = activeLineWidth;
                break;

            case BlobState.HIDDEN:
                blobLine.colorGradient    = passiveColour;
                wobbleActive              = 1;
                blobLine.widthMultiplier *= 0.5f;
                lineWidth = passiveLineWidth;
                break;
            }
        }
    }
Exemplo n.º 2
0
    private void Jump(Vector2 jumpVector)
    {
        // Can't jump in mid air
        if (currentState != BlobState.ON_WALL)
        {
            Debug.Log("Not on wall - can't jump");
            return;
        }

        // Didn't drag enough to register swipe
        if (jumpVector.sqrMagnitude < minDragDistance)
        {
            Debug.Log("Not enough drag to jump");
            return;
        }

        // Drag is towards the wall we're stuck on
        if (!CheckJumpAngle(currentDirection, jumpVector, jumpAngleLimit))
        {
            Debug.Log("Trying to jump to wall we're on");
            return;
        }

        // Jumping:
        Debug.Log("Jumping to: " + jumpVector);
        body.velocity = jumpVector.normalized * jumpSpeed;
        currentState  = BlobState.JUMPING;
        animator.SetBool(animJumping, true);
        ChangeSpriteDirection();
        angleDisplay.Hide();
        jumpsNum++;
    }
Exemplo n.º 3
0
    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "JumpingPad")
        {
            JumpTrigger();
        }

        if (other.tag == "PositionTrigger")
        {
            TriggerNextPosition();
        }

        if (other.tag == "DeathZone")
        {
            state = BlobState.Dead;
            RemoveFromList();
            gameObject.SetActive(false);

            if (blobDied != null)
            {
                blobDied(this);
            }
        }
        if (other.tag == "WinningTrigger")
        {
            state = BlobState.InGoal;
            Invoke("DisableRigidBody", UnityEngine.Random.Range(0.4f, 1f));
            if (blobSaved != null)
            {
                blobSaved(this);
            }
        }
    }
Exemplo n.º 4
0
    public void Restart()
    {
        gameOverScreen.SetActive(false);
        angleDisplay.Hide();

        body.position = startingPosition;
        body.velocity = initialVelocity.normalized * jumpSpeed;

        jumpsNum         = 0;
        facingUp         = true;
        currentState     = initialState;
        currentDirection = initialDirection;

        // Allows starting with jump or with sticking to wall
        if (currentState == BlobState.JUMPING)
        {
            animator.Play("Blob_Jump");
            animator.SetBool(animJumping, true);
        }
        else
        {
            animator.Play("Blob_OnWall");
            animator.SetBool(animJumping, false);
        }

        ChangeSpriteDirection();
    }
Exemplo n.º 5
0
 void CopyMaterialToState(Material material, ref BlobState state)
 {
     state._FresnelBias         = material.GetFloat("_FresnelBias");
     state._FresnelPow          = material.GetFloat("_FresnelPow");
     state._FresnelIntensity    = material.GetFloat("_FresnelIntensity");
     state._ReflectionIntensity = material.GetFloat("_ReflectionIntensity");
 }
        /// <summary>
        /// Stores <paramref name="state"/> in the repository with the specified <paramref name="key"/>.
        /// If there is already a state stored with the same key, it will be replaced by <paramref name="state"/>.
        /// </summary>
        /// <typeparam name="T">The type of the state. The repository will store the state in the repository as a JSON-serialized string.</typeparam>
        /// <param name="key">The state's key (case insensitive).</param>
        /// <param name="state">The state to store.</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>A <see cref="Task"/> object that represents the asynchronous operation.</returns>
        /// <exception cref="System.ArgumentNullException">This exception is thrown if the key or the state are null.</exception>
        /// <exception cref="StateSerializationException">This exception is thrown if state serialization fails.</exception>
        /// <exception cref="StateTooBigException">This exception is thrown if serialized state exceeds allowed length.</exception>
        /// <exception cref="FailedToSaveStateException">This exception is thrown if state saving failed due to an internal error.</exception>
        public Task StoreStateAsync <T>(string key, T state, CancellationToken cancellationToken)
        {
            Diagnostics.EnsureArgumentNotNull(() => key);

            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            key = key.ToUpperInvariant();

            this.tracer.TraceInformation($"Serializing state for Smart Detector {this.smartDetectorId} and rule {this.alertRuleResourceId}");
            string serializedState;

            try
            {
                serializedState = JsonConvert.SerializeObject(state);
            }
            catch (Exception ex)
            {
                throw new StateSerializationException(ex);
            }

            if (serializedState.Length > MaxSerializedStateLength)
            {
                throw new StateTooBigException(serializedState.Length, MaxSerializedStateLength);
            }

            this.tracer.TraceInformation($"Compressing state for Smart Detector {this.smartDetectorId} and rule {this.alertRuleResourceId}");
            string compressedSerializedState = CompressString(serializedState);

            BlobState blobState = new BlobState
            {
                Key                 = key,
                SmartDetectorId     = this.smartDetectorId,
                AlertRuleResourceId = this.alertRuleResourceId,
                State               = compressedSerializedState
            };

            string serializedBlobState = JsonConvert.SerializeObject(blobState);

            this.tracer.TraceInformation($"Uploading state to '{this.GenerateBlobName(key)}' for Smart Detector {this.smartDetectorId} and rule {this.alertRuleResourceId}");
            Task <ICloudBlob> uploadBlobTask;

            try
            {
                uploadBlobTask = this.cloudBlobContainerWrapper.UploadBlobAsync(this.GenerateBlobName(key), serializedBlobState, cancellationToken);
            }
            catch (Exception ex)
            {
                throw new FailedToSaveStateException(ex);
            }

            this.tracer.TraceInformation($"Successfully uploaded state for Smart Detector {this.smartDetectorId} and rule {this.alertRuleResourceId}");

            return(uploadBlobTask);
        }
Exemplo n.º 7
0
 // Change state.
 public void ChangeState(BlobState newState)
 {
     if (currentState != null)
     {
         currentState.Leave();
     }
     currentState = newState;
     currentState.Enter();
 }
Exemplo n.º 8
0
    void LerpCurParamsTo(BlobState to)
    {
        float t = 8f * Time.deltaTime;

        cur._FresnelBias         = Mathf.MoveTowards(cur._FresnelBias, to._FresnelBias, t);
        cur._FresnelPow          = Mathf.MoveTowards(cur._FresnelPow, to._FresnelPow, t);
        cur._FresnelIntensity    = Mathf.MoveTowards(cur._FresnelIntensity, to._FresnelIntensity, t);
        cur._ReflectionIntensity = Mathf.MoveTowards(cur._ReflectionIntensity, to._ReflectionIntensity, t);
        cur._Saturation          = Mathf.MoveTowards(cur._Saturation, to._Saturation, t);
    }
Exemplo n.º 9
0
    public virtual void GetThrown(Vector3 startPosition, Vector3 endPosition)
    {
        transform.position = startPosition;
        State = BlobState.Flying;
        blobAnimator.SetBool("isFlying", true);

        float duration = Vector3.Distance(startPosition, endPosition) / throwSpeed;

        PlayThrowSound();
        transform.DOJump(endPosition, throwHeight, 1, duration).OnComplete(OnLanding);
    }
Exemplo n.º 10
0
    void OnCollisionEnter2D(Collision2D collision)
    {
        // Stop movement and jumping animation
        body.velocity = Vector2.zero;
        animator.SetBool(animJumping, false);

        // Check collision direction
        ContactPoint2D[] contactPoints = new ContactPoint2D[2];
        collision.GetContacts(contactPoints);
        Vector2 firstContact  = contactPoints[0].point;
        Vector2 secondContact = contactPoints[1].point;

        // We've hit a vertical wall
        if (Mathf.Approximately(firstContact.x, secondContact.x))
        {
            if (firstContact.x > transform.position.x)
            {
                currentDirection = Direction.LEFT;
            }
            else
            {
                currentDirection = Direction.RIGHT;
            }
        }
        else     // We've probably hit a horizontal wall
        {
            if (firstContact.y > transform.position.y)
            {
                currentDirection = Direction.DOWN;
            }
            else
            {
                currentDirection = Direction.UP;
            }
        }

        if (collision.transform.CompareTag("Spike"))
        {
            currentState = BlobState.DEAD;
            animator.SetTrigger(animDied);
            gameOverScreen.SetActive(true);
        }

        if (collision.transform.CompareTag("Wall"))
        {
            currentState = BlobState.ON_WALL;
        }

        ChangeSpriteDirection();
    }
Exemplo n.º 11
0
    // Update is called once per frame
    void Update()
    {
        BlobState targetState = (playerController.isMuted) ? muted : normal;

        LerpCurParamsTo(targetState);
        CopyParamsToBlob();

        //player health
        float playerHealth = 1f - (playerController.playerHealth / 100f);

        blobMat.material.SetFloat("_NoiseAmp", dyingNoiseAmp.Evaluate(playerHealth));
        blobMat.material.SetFloat("_NoiseFreq", dyingNoiseFreq.Evaluate(playerHealth));
        blobMat.material.SetFloat("_SpikeAmp", dyingSpikeAmp.Evaluate(playerHealth));
        blobMat.material.SetFloat("_Size", dyingSize.Evaluate(playerHealth));
    }
Exemplo n.º 12
0
    private IEnumerator Wander()
    {
        blobState = BlobState.Wandering;
        //get random direction
        var randomAngle     = Random.Range(0f, Mathf.PI * 2f);
        var randomDirection = new Vector2(Mathf.Sin(randomAngle), Mathf.Cos(randomAngle)).normalized;

        //wander in random direction for x seconds
        var wanderTime = Random.Range(minWanderTime, maxWanderTime);

        while (wanderTime > 0)
        {
            _rigidbody.AddForce(randomDirection * moveSpeed, ForceMode.VelocityChange);
            wanderTime -= Time.deltaTime;
            yield return(null);
        }
        StartCoroutine(Wander());
    }
Exemplo n.º 13
0
    private IEnumerator GetFood(FruitLogic targetFoodScript)
    {
        blobState = BlobState.MovingToFood;
        // move towards found food
        var blobPositon  = transform.position;
        var foodPosition = targetFoodScript.transform.position;

        var distanceToFood    = Vector3.Distance(blobPositon, foodPosition);
        var vectorTowardsFood = (blobPositon - foodPosition).normalized;

        while (distanceToFood > eatingRange)
        {
            _rigidbody.AddForce(vectorTowardsFood * moveSpeed, ForceMode.VelocityChange);
            distanceToFood    = Vector3.Distance(transform.position, targetFoodScript.transform.position);
            vectorTowardsFood = (blobPositon - foodPosition).normalized;
            yield return(null);
        }
        StartCoroutine(EatFood(targetFoodScript));
    }
Exemplo n.º 14
0
    internal virtual void SearchInteractables()
    {
        RaycastHit[]           hits                = Physics.SphereCastAll(transform.position, interactionRange, Vector3.up, 0, interactableLayerMask);
        List <EnemyController> nearbyEnemies       = new List <EnemyController>();
        List <Interactable>    nearbyInteractables = new List <Interactable>();

        foreach (var hit in hits)
        {
            EnemyController enemy = hit.collider.GetComponent <EnemyController>();
            if (enemy != null)
            {
                nearbyEnemies.Add(enemy);
                continue;
            }

            Interactable interactable = hit.collider.GetComponent <Interactable>();
            if (interactable != null && interactable.CanBeAssigned(this))
            {
                nearbyInteractables.Add(interactable);
            }
        }

        if (nearbyEnemies.Count > 0)
        {
            // Attack closest enemy
            var closestEnemy = Helper.GetClosestObject(nearbyEnemies.ToArray(), transform.position);
            currentInteractable = closestEnemy;
            State = closestEnemy.AssignBlob(this);
            return;
        }

        if (nearbyInteractables.Count > 0)
        {
            // Interact with closest interactable
            currentInteractable = Helper.GetClosestObject(nearbyInteractables.ToArray(), transform.position);
            State = currentInteractable.AssignBlob(this);
            return;
        }
    }
Exemplo n.º 15
0
 internal static HandleRef getCPtr(BlobState obj) {
   return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Exemplo n.º 16
0
 public virtual void StartFollowing(Transform target)
 {
     State        = BlobState.Following;
     followTarget = target;
     PlayAudioClip(callSounds[Random.Range(0, callSounds.Length)]);
 }
Exemplo n.º 17
0
 public virtual void StartInteracting(Interactable target)
 {
     State = BlobState.Interacting;
     currentInteractable = target;
     PlayAudioClip(callSounds[Random.Range(0, callSounds.Length)]);
 }
Exemplo n.º 18
0
 public virtual void OnLanding()
 {
     State = BlobState.Idle;
     blobAnimator.SetBool("isFlying", false);
     SearchInteractables();
 }
Exemplo n.º 19
0
 private void Awake()
 {
     rb    = GetComponent <Rigidbody>();
     state = BlobState.Alive;
 }
Exemplo n.º 20
0
 internal void InitializeBaseBlob()
 {
     State = BlobState.Idle;
     navMeshAgent.speed = movementSpeed;
 }
Exemplo n.º 21
0
 internal static HandleRef getCPtr(BlobState obj)
 {
     return((obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr);
 }
Exemplo n.º 22
0
        /// <summary>
        /// Gets a Smart Detector's state that was saved with <paramref name="key"/>.
        /// If state does not exist, returns <code>default(<typeparamref name="T"/>)</code>.
        /// </summary>
        /// <typeparam name="T">The type of the state. The repository will try to JSON-deserialize the stored state to this type.</typeparam>
        /// <param name="key">The key that was used to store the state (case insensitive).</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>A <see cref="Task"/> object that represents the asynchronous operation, returning the requested state.</returns>
        /// <exception cref="System.ArgumentNullException">This exception is thrown if the key is null.</exception>
        /// <exception cref="StateSerializationException">This exception is thrown if state deserialization fails.</exception>
        /// <exception cref="FailedToLoadStateException">This exception is thrown if state retrieval failed due to an internal error.</exception>
        public async Task <T> GetStateAsync <T>(string key, CancellationToken cancellationToken)
        {
            Diagnostics.EnsureArgumentNotNull(() => key);

            key = key.ToLowerInvariant();

            this.tracer.TraceInformation($"Downloading state from '{this.GenerateBlobName(key)}' for {smartDetectorId}");
            string serializedBlobState = null;

            try
            {
                serializedBlobState = await this.cloudBlobContainerWrapper.DownloadBlobContentAsync(this.GenerateBlobName(key), cancellationToken);
            }
            catch (StorageException ex) when((HttpStatusCode)ex.RequestInformation.HttpStatusCode == HttpStatusCode.NotFound)
            {
                this.tracer.TraceInformation("State not found in the repository, returning empty state");
                return(default(T));
            }
            catch (Exception ex)
            {
                throw new FailedToLoadStateException(ex);
            }

            this.tracer.TraceInformation($"Deserializing state for {smartDetectorId}");
            BlobState blobState = null;

            try
            {
                blobState = JsonConvert.DeserializeObject <BlobState>(serializedBlobState);
            }
            catch (Exception ex)
            {
                this.tracer.ReportException(ex);
                this.tracer.TraceError("Blob state deserialization failed, trying to delete the state and returning empty state");

                // Try to delete the state
                await this.TryDeleteStateAsync(key, cancellationToken);

                return(default(T));
            }

            if (string.Equals(blobState.SmartDetectorId, this.smartDetectorId) == false || string.Equals(blobState.Key, key) == false)
            {
                this.tracer.TraceError("State does not match expected Smart Detector id or key, trying to delete the state and returning empty state");

                // Try to delete the state
                await this.TryDeleteStateAsync(key, cancellationToken);

                return(default(T));
            }

            if (string.IsNullOrWhiteSpace(blobState.State))
            {
                return(default(T));
            }

            string compressedSerializedState = blobState.State;

            this.tracer.TraceInformation($"Decompressing state for {smartDetectorId}");
            string serializedState = DecompressString(compressedSerializedState);

            T state = default(T);

            try
            {
                state = JsonConvert.DeserializeObject <T>(serializedState);
            }
            catch (Exception ex)
            {
                throw new StateSerializationException(ex);
            }

            this.tracer.TraceInformation($"Successfully retrieved state for {smartDetectorId}");

            return(state);
        }