void CheckIfGrounded()
    {
        Debug.Log(m_CapsuleCollider2D.bounds.size);
        RaycastHit2D[] hits;
        hits = Physics2D.CapsuleCastAll(new Vector2(transform.position.x, transform.position.y) + m_CapsuleCollider2D.offset, m_CapsuleCollider2D.bounds.size * 0.95f, CapsuleDirection2D.Vertical, 0f, Vector2.down, 1 / 16f, LayerMask.GetMask("Ground"));

        if (hits.Length >= 1)
        {
            foreach (RaycastHit2D hit in hits)
            {
                if (Vector2.Angle(transform.up, hit.normal) < 45f)
                {
                    m_IsGrounded = true;

                    // Tocamos el suelo después de falling
                    if (m_AnimationState == AnimationStates.FALLING)
                    {
                        // TRANSICION A RUNNING DESDE LANDING
                        SwitchState(AnimationStates.LANDING);
                    }
                    break;
                }
            }
        }
        else
        {
            m_IsGrounded     = false;
            m_AnimationState = AnimationStates.FALLING;
            m_PlayerAnimator.SetInteger("AnimationState", 8);
        }
    }
Exemple #2
0
        public IEnumerable <RaycastHit2D> CastAll(Vector2 colliderPosition, float colliderAngle, Vector2 direction, float distance, ColliderSkin colliderToUse)
        {
            float skinOffset = GetSkinWidthForDirection(direction, colliderToUse);
            IEnumerable <RaycastHit2D> hits = null;

            switch (geometry.colliderType)
            {
            case ColliderType.Box:
                hits = RoundedBoxCastAll(colliderPosition + offset, GetSkinnedColliderSize(colliderToUse), GetSkinnedColliderRadius(colliderToUse), colliderAngle, direction.normalized, distance - skinOffset, interactionMask);
                break;

            case ColliderType.Capsule:
                hits = Physics2D.CapsuleCastAll(colliderPosition + offset, GetSkinnedColliderSize(colliderToUse), colliderDirection, colliderAngle, direction, distance - skinOffset, interactionMask);
                break;

            case ColliderType.Circle:
                hits = Physics2D.CircleCastAll(colliderPosition + offset, GetSkinnedColliderRadius(colliderToUse), direction.normalized, distance - skinOffset, interactionMask);
                break;

            default:
                Debug.LogError("Invalid or unset Collider2D (KMGMovement2D only supports CircleCollider2D, BoxCollider2D, and CapsuleCollider2D).");
                return(null);
            }
            return(hits.Select(delegate(RaycastHit2D x) {
                x.distance += skinOffset;
                return x;
            }));
        }
    void CheckIfGrounded()
    {
        RaycastHit2D[] hits;
        hits = Physics2D.CapsuleCastAll(new Vector2(transform.position.x, transform.position.y), m_CapsuleCollider2D.bounds.size, CapsuleDirection2D.Vertical, 0f, Vector2.down, 0.05f, LayerMask.GetMask("Ground"));

        if (hits.Length >= 1)
        {
            m_IsGrounded = true;
        }
        else
        {
            m_IsGrounded = false;
        }
    }
Exemple #4
0
    public RaycastHit2D[] CheckAllCasts(Vector2 posOfs, float reduceOfs, Vector2 dir, float dist, int mask)
    {
        if (mCapsuleColl)
        {
            Transform collT    = transform;
            Vector2   collPos  = collT.position + collT.localToWorldMatrix.MultiplyPoint3x4(mCapsuleColl.offset + posOfs);
            Vector2   collSize = mCapsuleColl.size; collSize.y -= reduceOfs;

            return(Physics2D.CapsuleCastAll(collPos, collSize, mCapsuleColl.direction, collT.eulerAngles.z, dir, dist, mask));
        }
        else
        {
            Transform collT   = transform;
            Vector2   collPos = collT.position + collT.localToWorldMatrix.MultiplyPoint3x4(posOfs);

            return(Physics2D.CircleCastAll(collPos, mRadius - reduceOfs, dir, dist, mask));
        }
    }
Exemple #5
0
        //This manages when to set everything back to the original values they were in prior to the dash; most of this logic is toggling between two different states. This also makes sure that if the player can't stand where they when finished dashing, it teleports player back to somewhere where they can stand.
        protected virtual IEnumerator FinishedDashing()
        {
            yield return(new WaitForSeconds(dashAmountTime));

            capsuleCollider2D.direction = CapsuleDirection2D.Vertical;
            capsuleCollider2D.size      = new Vector2(capsuleCollider2D.size.y, capsuleCollider2D.size.x);
            anim.SetBool("Dashing", false);
            character.isDashing = false;
            FallSpeed(1);
            movement.enabled = true;
            rb.velocity      = new Vector2(0, rb.velocity.y);
            RaycastHit2D[] hits = new RaycastHit2D[10];
            yield return(new WaitForSeconds(.1f));

            hits = Physics2D.CapsuleCastAll(new Vector2(col.bounds.center.x, col.bounds.center.y + .05f), new Vector2(col.bounds.size.x, col.bounds.size.y - .1f), CapsuleDirection2D.Vertical, 0, Vector2.zero, 0, jump.collisionLayer);
            if (hits.Length > 0)
            {
                transform.position = deltaPosition;
            }
        }
Exemple #6
0
    void FixedUpdate()                                                                                                                                         //Only Here For One Update, If Nothing Is Hit, The 'Spell' Is Destroyed
    {
        foreach (RaycastHit2D s in Physics2D.CapsuleCastAll(transform.position, TheCapsuleSize, CapsuleDirection2D.Vertical, 0, Vector2.zero, 0, WhatCanIHit)) //Capsule size is acting weird. the y value is the radius of the height, but the x value is the diameter of the width?????? WHAT why......

        {
            targets = s.transform.GetComponent <CreatureRoot> ();
            if (targets != null)
            {
                if (targets.Stats.HealthImmunity == false && targets.Stats.TotalImmunity == false)
                {
                    if (dmg * (1 - targets.Stats.PhysicalResistence) > 0)                      //If The Creature Have Resist > 1 Then The Attack Will Heal The Creature. Fire On Fire Might Heal?
                    {
                        targets.TookDmg(Mathf.CeilToInt(dmg * (1 - targets.Stats.PhysicalResistence)));
                    }
                }
            }
        }

        Destroy(gameObject);
    }
    void Move()
    {
        //Monedas
        m_Coins           = m_Coins + Mathf.Abs(Vector3.Distance(m_PosAnt, transform.position));
        m_PosAnt          = transform.position;
        m_CoinsCount.text = " " + (int)m_Coins;

        Vector2 desiredVelocity = new Vector2(m_MovementSpeed * m_direction, m_Rigidbody2D.velocity.y);

        RaycastHit2D[] hits = Physics2D.CapsuleCastAll(new Vector2(transform.position.x, transform.position.y) + m_CapsuleCollider2D.offset, m_CapsuleCollider2D.bounds.size, CapsuleDirection2D.Horizontal, 0f, Vector2.right * m_direction, m_Rigidbody2D.velocity.x * Time.deltaTime, LayerMask.GetMask("Ground"));


        if (hits.Length >= 1)
        {
            desiredVelocity.x = 0;
        }
        m_Rigidbody2D.velocity = desiredVelocity;

        Debug.Log(Physics2D.gravity);
        m_IsMoving = true;
    }
    void Move()
    {
        Vector2 desiredVelocity = new Vector2(m_MovementSpeed * m_Orientation, m_Rigidbody2D.velocity.y);

        RaycastHit2D[] hits = Physics2D.CapsuleCastAll(new Vector2(transform.position.x, transform.position.y) + m_CapsuleCollider2D.offset,
                                                       m_CapsuleCollider2D.bounds.size * 0.95f, CapsuleDirection2D.Horizontal, 0f, Vector2.right * m_Orientation,
                                                       m_Rigidbody2D.velocity.x * Time.deltaTime, LayerMask.GetMask("Ground"));


        if (hits.Length >= 1)
        {
            foreach (RaycastHit2D hit in hits)
            {
                if (Vector2.Angle(hit.normal, desiredVelocity) >= 90)
                {
                    desiredVelocity.x = 0;
                }
            }
        }
        m_Rigidbody2D.velocity = desiredVelocity;
    }
Exemple #9
0
        public override void OnEnter()
        {
            var col = collection.Value;

            if (col != null)
            {
                RaycastHit2D[] resHits = null;

                switch (castType)
                {
                case CastType.Box:
                    resHits = Physics2D.BoxCastAll(position1.Value, shapeSize.Value, shapeAngle.Value, direction.Value, maxDistance.Value, layerMask.value, minDepth.Value, maxDepth.Value);
                    break;

                case CastType.Capsule:
                    resHits = Physics2D.CapsuleCastAll(position1.Value, shapeSize.Value, capsuleDirection, shapeAngle.Value, direction.Value, maxDistance.Value, layerMask.value, minDepth.Value, maxDepth.Value);
                    break;

                case CastType.Circle:
                    resHits = Physics2D.CircleCastAll(position1.Value, radius.Value, direction.Value, maxDistance.Value, layerMask.value, minDepth.Value, maxDepth.Value);
                    break;

                case CastType.Line:
                    resHits = Physics2D.LinecastAll(position1.Value, lineEnd.Value, layerMask.value, minDepth.Value, maxDepth.Value);
                    break;

                case CastType.Ray:
                    resHits = Physics2D.RaycastAll(position1.Value, direction.Value, maxDistance.Value, layerMask.value, minDepth.Value, maxDepth.Value);
                    break;

                default:
                    break;
                }

                PutCollidersIntoGameObjectCollection(resHits);
            }

            Continue();
        }
Exemple #10
0
    private void CheckForHits()
    {
        //Simply checks the distance between the ball before and after moving in this same update cycle.
        //If the ball hits something, the first thing hit is checked, then the next, etc. If it hits something,
        //it returns, not hitting any other targets.
        if (fireState != FireState.Live)
        {
            return;
        }

        Vector2 currentPos = new Vector2(transform.position.x, transform.position.y);
        //RaycastHit2D[] hits = Physics2D.RaycastAll(previousPos, (currentPos - previousPos).normalized, (currentPos - previousPos).magnitude);

        SpriteRenderer tempRend = GetComponentInChildren <SpriteRenderer>();

        RaycastHit2D[] hits = Physics2D.CapsuleCastAll(previousPos, new Vector2(tempRend.size.x / 2, tempRend.size.y / 2), CapsuleDirection2D.Horizontal, 0, velocity, (currentPos - previousPos).magnitude, PhysicsLayers.LayerMask((int)Layer.AttackOrb));

        for (int i = 0; i < hits.Length; i++)
        {
            HitTrigger(hits[i].collider);
        }
    }
Exemple #11
0
    private IEnumerator Charge(float distance, float chargeSpeed = 0.25f)
    {
        charging    = true;
        dealtDamage = false;
        yield return(new WaitForSeconds(0.4f)); //0.4 sec delay

        Vector2 direction = (Global.player.transform.position - transform.position).normalized;
        Vector2 chargeEnd = (Vector2)transform.position + direction * distance;

        yield return(new WaitForSeconds(0.3f)); //0.3 sec to dodge after aiming

        RaycastHit2D[] hits;
        while (Vector2.Distance(transform.position, chargeEnd) > Mathf.Epsilon)
        {
            int divide = 20; //divide the distance into n parts to prevent passing through walls
            for (int i = 0; i < divide; i++)
            {
                hits = Physics2D.CapsuleCastAll((Vector2)transform.position + col.offset, col.bounds.size, col.direction, 0.0f, direction, chargeSpeed / divide);
                if (hits.Any(hit => hit.collider.gameObject.tag == "Wall"))   //collided with a wall
                {
                    charging = false;
                    yield break;
                }

                transform.position = Vector2.MoveTowards(transform.position, chargeEnd, chargeSpeed / divide);
                if (!dealtDamage && col.IsTouching(Global.player.GetComponent <CapsuleCollider2D>()))
                {
                    //if this charge hits the player, deal damage to player
                    dealtDamage = true;
                    Global.player.GetComponent <PlayerStats>().DealDamage(GetComponent <EnemyStats>().damage);
                }
            }
            transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.y);
            yield return(null);
        }

        charging = false;
    }
Exemple #12
0
    public void StartImpact()
    {
        Active = true;
        impactedList.ForEach(entity => ApplyDamage(entity));
        if (ImpactType == ImpactType.OnEntity)
        {
            ApplyDamage(Creator);
            if (ImpactLifeCycle == ImpactLifeCycle.DestructOnHit)
            {
                Deactivate();
            }
        }

        else if (ImpactType == ImpactType.ColliderCast)
        {
            var hitEntities = new List <GameEntity>();
            var box         = GetComponentInChildren <BoxCollider2D>();
            var circle      = GetComponentInChildren <CircleCollider2D>();
            var capsule     = GetComponentInChildren <CapsuleCollider2D>();
            var pos         = box
                ? transform.localToWorldMatrix.MultiplyPoint(box.offset)
                : circle
                    ? transform.localToWorldMatrix.MultiplyPoint(circle.offset)
                    : capsule
                        ? transform.localToWorldMatrix.MultiplyPoint(capsule.offset)
                        : transform.position;

            if (box)
            {
                var hits = Physics2D.OverlapBoxAll(pos, box.size, box.transform.eulerAngles.z, DamageLayerMask);

                hitEntities.AddRange(
                    hits.Select(hit => hit.transform.GetComponentInParent <GameEntity>())
                    .Where(entity => entity)
                    .ToList());
            }
            if (circle)
            {
                var hits = Physics2D.CircleCastAll(pos, circle.radius, Vector2.zero, 0, DamageLayerMask);
                hitEntities.AddRange(
                    hits.Select(hit => hit.transform.GetComponentInParent <GameEntity>())
                    .Where(entity => entity)
                    .ToList());
            }
            if (capsule)
            {
                var hits = Physics2D.CapsuleCastAll(pos, capsule.size, capsule.direction, 0, Vector2.zero, 0, DamageLayerMask);
                hitEntities.AddRange(
                    hits.Select(hit => hit.transform.GetComponentInParent <GameEntity>())
                    .Where(entity => entity)
                    .ToList());
            }
            hitEntities
            .Distinct()
            .ForEach(entity => ApplyDamage(entity));
            EndImpact();
        }
        else if (ImpactType == ImpactType.WholeScene)
        {
            Resources.FindObjectsOfTypeAll <GameEntity>()
            .Where(entity => entity.gameObject.scene != null)
            .ForEach(entity => ApplyDamage(entity));
        }
        else if (ImpactType == ImpactType.ChaseEntity)
        {
            if (!TargetEntity || !GetComponent <ChaseObject>())
            {
                return;
            }
            GetComponent <ChaseObject>().Target           = TargetEntity.transform;
            GetComponent <ChaseObject>().InitialDirection = Direction;
        }
    }
Exemple #13
0
        private void CollisionChecks()
        {
            //We now only set the object to grounded by collision. This works more reliably
            capsuleBottom = new Vector3(
                quickCapsule.offset.x * Mathf.Abs(transform.lossyScale.x) + transform.position.x,
                quickCapsule.offset.y * transform.lossyScale.y + transform.position.y,
                transform.position.z);                 //Whim: Forgot to remove Transform Point here. This caused the center to be far off into the distance
            Vector2 quickNormal       = Vector2.zero;
            Vector2 quickTotalNormals = Vector2.zero;
            Vector2 quickAvgNormal    = Vector2.zero;
            int     quickTotal        = 0;

            rayHits = new List <RaycastHit2D>();

            //Whim: A parameter to find the shortest distance from a wall
            myWallFollow = Mathf.Infinity;

            //Set the normals from a check flat in size
            if (priv_Grounded)
            {
                foreach (RaycastHit2D repHit in
                         Physics2D.RaycastAll(
                             (Vector2)capsuleBottom,                                                                                                                          //Origin. Place the check from the center of the character
                             Vector2.down,                                                                                                                                    //Direction, down of course
                             0.3f + Mathf.Abs(myVelocity.x * Time.deltaTime / Mathf.Tan(slipAngle * Mathf.Deg2Rad) * 3f) + quickCapsule.size.y / 2f * transform.lossyScale.y, //The distance has the speed accounted for, and the gap for when on a slope
                             Physics2D.GetLayerCollisionMask(LayerMask.NameToLayer("PlayerLayer")))                                                                           //The mask
                         )
                {
                    if (repHit.normal.y < Mathf.Cos(slipAngle * Mathf.Deg2Rad) || repHit.distance - quickCapsule.size.y / 2f * transform.lossyScale.y <= -0.1f)
                    {
                        continue;
                    }

                    quickTotalNormals += repHit.normal;
                    quickTotal++;
                }

                //Do this check to accurately see if you're standing on a platform, and to get a good value for myFollow
                foreach (RaycastHit2D repHit in
                         Physics2D.CapsuleCastAll(
                             (Vector2)capsuleBottom,                                                                                             //origin
                             new Vector2(quickCapsule.size.x * Mathf.Abs(transform.lossyScale.x), quickCapsule.size.y * transform.lossyScale.y), //size
                             quickCapsule.direction,                                                                                             //capsuleDirection
                             0f,                                                                                                                 //angle (it may be 90)
                             Vector2.down,                                                                                                       //raycast direction
                             0.2f + Mathf.Abs(myVelocity.x * Time.deltaTime / Mathf.Tan(slipAngle * Mathf.Deg2Rad) * 3f),                        //Raycast distance.
                             Physics2D.GetLayerCollisionMask(LayerMask.NameToLayer("PlayerLayer"))                                               //Collision mask
                             )
                         )
                {
                    //Debug.Log(repHit.collider.gameObject.name);
                    if (repHit.normal.y < Mathf.Cos(slipAngle * Mathf.Deg2Rad) || repHit.distance <= -0.1f)
                    {
                        continue;
                    }

                    if (repHit.distance - 0.01f < myWallFollow)
                    {
                        myWallFollow = repHit.distance - 0.01f;
                    }
                    rayHits.Add(repHit);
                }
            }
            //Debug.Log(rayHits.Count);
            if (rayHits.Count == 0)
            {
                priv_Grounded = false;
                myWallFollow  = 0f;
                avgNormAngle  = 0f;
            }
            else
            {
                priv_Grounded = true;
                stateAerial   = PlayerStateAerial.No;
                float slowDownSpeed = myOriginalMaxSpeed / 2f + (myOriginalMaxSpeed * (1f - Mathf.InverseLerp(steepAngle, slipAngle, Mathf.Abs(avgNormAngle) * Mathf.Rad2Deg)) / 2f);
                float speedUpSpeed  = myOriginalMaxSpeed + (myOriginalMaxSpeed * (Mathf.InverseLerp(speedUpAngle, slipAngle, Mathf.Abs(avgNormAngle) * Mathf.Rad2Deg)) / 3f);
                if (quickTotal > 0)
                {
                    quickAvgNormal = quickTotalNormals / (float)quickTotal;
                    avgNormAngle   = Mathf.Atan2(quickTotalNormals.y / (float)quickTotal, quickTotalNormals.x / (float)quickTotal) - Mathf.PI / 2f;
                }
                else
                {
                    myWallFollow = 0;
                }
                myWallFollow = ((myWallFollow > 0.03 && quickTotal > 0) ? myWallFollow : 0f);
                if (quickAvgNormal.y < Mathf.Cos(steepAngle * Mathf.Deg2Rad) && myVelocity.y > 0)
                {
                    myMaxSpeed = slowDownSpeed;
                }
                if (quickAvgNormal.y >= -Mathf.Cos(speedUpAngle * Mathf.Deg2Rad) && myVelocity.y < 0)
                {
                    myMaxSpeed = speedUpSpeed;
                }
            }
            Debug.Log("" + Mathf.Round(myVelocity.magnitude * 100f) / 100f + ", " + Mathf.Round(myMaxSpeed * 100f) / 100f + ", " + Mathf.Round(avgNormAngle * Mathf.Rad2Deg * 100f) / 100f + ", " + Mathf.Round(quickAvgNormal.y * 100f) / 100f);
            priv_Anim.SetBool("Ground", priv_Grounded);
            // This tracks how long the character's been in the air
            // There's a threshold for this frame counter during which the player can still jump
            // Theoretically this could allow for more than 1 jump in midair, but it's too small a timespan to be of much use anyhow
            if (!priv_Grounded)
            {
                airborneFrames++;
            }
            else
            {
                airborneFrames = 0;
            }
            // Handles the jump buffer
            // If a player presses jump right before landing, this ensures the command still goes through
            // This makes the game feel more responsive
            if (priv_jumpInput)
            {
                jumpBufferFrames++;
            }
            if (jumpBufferFrames > jumpBufferReset)
            {
                jumpBufferFrames = 0;
                priv_jumpInput   = false;
                Debug.Log("reset");
            }

            // Set the vertical animation
            priv_Anim.SetFloat("vSpeed", myVelocity.y);
        }
Exemple #14
0
    //void OnCollisionEnter2D(Collision2D collision)
    //{
    //    //isGrounded = false;
    //    foreach (ContactPoint2D contact in collision.contacts)
    //    {
    //        if (Vector2.Dot(transform.up, contact.normal) > 0)
    //        {
    //            //isGrounded = true;
    //            groundedCount++;
    //            Debug.Log(groundedCount + " " + Time.frameCount);
    //            //return;
    //        }
    //    }
    //}

    //void OnCollisionExit2D(Collision2D collision)
    //{
    //    //isGrounded = false;
    //    foreach (ContactPoint2D contact in collision.contacts)
    //    {
    //        if (Vector2.Dot(transform.up, contact.normal) > 0)
    //        {
    //            //isGrounded = true;
    //            groundedCount--;
    //            Debug.Log(groundedCount + " " + Time.frameCount);
    //            //return;
    //        }
    //    }
    //}


    bool CheckGrounded()
    {
        RaycastHit2D[] hits = Physics2D.CapsuleCastAll(transform.position, new Vector2(1, 2), CapsuleDirection2D.Vertical, transform.rotation.eulerAngles.z, -transform.up, 0.1f, LayerMask.GetMask("Default"));
        return(hits.Length > 0);
    }