コード例 #1
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        //barrierDirection keeps a list of last two barriers encountered

        //Colliders to turn away from
        if (collision.gameObject == brick || collision.gameObject.CompareTag("Enemy") || collision.gameObject == water || collision.gameObject == concrete ||
            collision.gameObject.CompareTag("Boundary") || collision.gameObject == eagle)
        {
            ContactPoint2D[] contacts = new ContactPoint2D[collision.contactCount];
            collision.GetContacts(contacts);

            if (barrierDirection.Count == 2)
            {
                barrierDirection.Remove(barrierDirection.First());
            }

            barrierDirection.Add(contacts[0].normal);
            WeightedRandomDirection();
        }

        //Colliders to turn to and shoot, then turn away
        else if (collision.gameObject.CompareTag("Player"))
        {
            if (!isTouchedByPlayer)
            {
                CancelInvoke("WeightedRandomDirection");

                ContactPoint2D[] contacts = new ContactPoint2D[collision.contactCount];
                collision.GetContacts(contacts);

                if (!contacts.All(c => Math.Round(c.normal.x) == Math.Round(contacts[0].normal.x)) &&
                    !contacts.All(c => Math.Round(c.normal.y) == Math.Round(contacts[0].normal.y)))
                {
                    throw new Exception("Multiple normal to contacts values from enemy-player collision");
                }

                moveDirection = contacts[0].normal * -1;

                gameObject.transform.rotation = SetRotation(moveDirection);

                CancelInvoke("Fire");
                Invoke("Fire", 0f);

                if (barrierDirection.Count == 2)
                {
                    barrierDirection.Remove(barrierDirection.First());
                }

                barrierDirection.Add(contacts[0].normal);

                Invoke("WeightedRandomDirection", 1f);
                //Invoke("WeightedRandomDirection", UnityEngine.Random.Range(minMoveChangeDelay, maxMoveChangeDelay));

                isTouchedByPlayer = true;
            }
        }
    }
コード例 #2
0
    private void TryMoveOpposite(Collision2D other)
    {
        if (!CanMove)
        {
            return;
        }

        int contactCount = other.GetContacts(contactCache);

        for (int i = 0; i < contactCount; i++)
        {
            // Debug.Log($"{gameObject.name} with normal {contactCache[i].normal}");

            if (contactCache[i].normal.y < 0.5f)
            {
                if (contactCache[i].normal.x == 1f)
                {
                    IsMovingLeft = false;
                }
                else if (contactCache[i].normal.x == -1f)
                {
                    IsMovingLeft = true;
                }

                break;
            }
        }
    }
コード例 #3
0
ファイル: StopSeed.cs プロジェクト: aluminu88/hamuchanGo
    void InstSprout(Collision2D collision)
    {
        if (collision.GetContacts(collision.contacts) <= 0)
        {
            return;
        }

        //接触点
        var contactPoint = collision.contacts[0].point;
        //接触点へのベクトル
        var contactDist = contactPoint - (Vector2)transform.position;

        contactDist.Normalize();

        float radius = Mathf.Atan2(contactDist.x, contactDist.y) * Mathf.Rad2Deg;

        if (135f <= Mathf.Abs(radius))//絶対値が135度以上なら床に当たっているとする
        {
            var instSprout = Instantiate(sprout, contactPoint, Quaternion.identity);
        }
        else
        {
            const float WallInstAngle = 30f;
            var         instSprout    = Instantiate(sprout, contactPoint, Quaternion.identity);
            if (0 <= contactDist.x)
            {
                instSprout.transform.Rotate(0, 0, WallInstAngle);
            }
            else
            {
                instSprout.transform.Rotate(0, 0, -WallInstAngle);
            }
        }
        Destroy(gameObject);
    }
コード例 #4
0
    private void OnCollisionStay2D(Collision2D collision)
    {
        if (platformMask.Contains(collision.gameObject.layer))
        {
            int count = collision.GetContacts(contactPoints);
            for (int i = 0; i < count; i++)
            {
                var newNormal = collision.GetContact(i).normal;

                if (!grounded || Vector2.Dot(platformNormal, newNormal) > 0.9f)  //FIXME how well normals align
                {
                    Debug.DrawRay(collision.GetContact(i).point, newNormal, Color.red);

                    platformNormal = newNormal;
                    platform       = collision.gameObject;
                    break;
                }

                //If walking into wall (=> velocity and normal point in opposite dirs, cos=-1)
                if (grounded && Vector2.Dot(velocity, newNormal) < -0.9f)
                {
                    platformNormal = newNormal;
                    platform       = collision.gameObject;

                    tangent  = new Vector2(platformNormal.y, -platformNormal.x);
                    velocity = localVelocity.x * tangent + localVelocity.y * platformNormal;
                }
            }
            grounded = true;
        }
    }
コード例 #5
0
    static public float GetCollMomentum(Collision2D coll, RbodyCollController collisionCont)
    {
        if (collisionCont == null)
        {
            return(0.0f);
        }


        // calculate momentum from ship
        float speedMomentum   = 0.0f;
        float angularMomentum = 0.0f;

        ContactPoint2D[] contacts = new ContactPoint2D[3];
        int num = coll.GetContacts(contacts);

        for (int i = 0; i < num; ++i)
        {
            ContactPoint2D contactPoint  = contacts[i];
            Vector2        dirToPoint    = contactPoint.point - collisionCont.worldCenterOfMass;
            float          circumference = 2.0f * Mathf.PI * dirToPoint.magnitude;
            float          angularSpeed  = (collisionCont.lastAngularVel / 360.0f) * circumference;
            Vector2        angularVel    = new Vector2(-dirToPoint.y, dirToPoint.x).normalized *angularSpeed;

            speedMomentum += Vector2.Dot(-contactPoint.normal, collisionCont.lastVel);
            float angularFactor = Vector2.Dot(-contactPoint.normal, angularVel) * 0.5F; // Reduce significance of angular momentum
            if (angularFactor > 0.0f)
            {
                angularMomentum += angularFactor;
            }
        }
        speedMomentum   /= num;
        angularMomentum /= num;
        return((speedMomentum + angularMomentum) * collisionCont.lastMass);
    }
コード例 #6
0
    private void OnCollisionEnter2D(Collision2D col)
    {
        var x = _force.x;
        var y = _force.y * -1;

        if (col.gameObject.name.Contains("pad"))
        {
            if (col.contactCount > 0)
            {
                var contacts = new ContactPoint2D[1];
                col.GetContacts(contacts);

                var contact = contacts[0];
                var bounds  = contact.collider.bounds;

                const float BALL_HEIGHT = 0.5f;

                y = contact.point.y.Remap(
                    (Mathf.Abs(bounds.min.y) + BALL_HEIGHT) * Mathf.Sign(bounds.min.y),
                    (Mathf.Abs(bounds.max.y) + BALL_HEIGHT) * Mathf.Sign(bounds.max.y),
                    -1,
                    1);
            }

            x *= -1;

            _speed *= SpeedIncrease;
        }

        _force = new Vector2(x, y);

        SoundHelper.Play(SoundHelper.Audios.Plop);
    }
コード例 #7
0
ファイル: CircleSaw.cs プロジェクト: DanilaTumanov/Runner
    private void StartBleed(GameObject GO, Collision2D collision)
    {
        IBleedable bleedableObj = GO.GetComponent <IBleedable>();

        if (bleedableObj != null)
        {
            GameObject       bloodGO  = bleedableObj.GetBloodGO();
            ParticleSystem   bloodPS  = bleedableObj.GetBloodPS();
            ContactPoint2D[] contacts = new ContactPoint2D[1];

            var bloodPSmain  = bloodPS.main;
            var bloodPSshape = bloodPS.shape;


            // Устанавливаем настройки для кровяки)
            bloodPSmain.startSpeed             = 7;
            bloodPSshape.randomDirectionAmount = 0.15f;

            // Получим точки соприкосновения коллайдеров
            collision.GetContacts(contacts);

            // Установим позицию кровотечения в точку соприкосновения
            bloodGO.transform.position = contacts[0].point;

            // Установим угол поворота перпендикулярным к нормали, для этого воспользуемся умножением векторов
            bloodGO.transform.rotation = Quaternion.FromToRotation(Vector3.right, Vector3.Cross(Vector3.forward, contacts[0].normal));

            // Включим анимацию
            bloodPS.Play();
        }
    }
コード例 #8
0
    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.collider.tag == "Enemy" && !invincible)
        {
            invincible = true;
            life       = life - 1;
            invTime    = Time.time + invLength;

            // lower opacity
            float b = sprite.material.color.b;
            float g = sprite.material.color.g;
            float r = sprite.material.color.r;
            sprite.material.SetColor("_Color", new Color(b, g, r, 0.5f));

            // bounce back
            float            force    = 1017.0f;
            ContactPoint2D[] contacts = new ContactPoint2D[1];
            other.GetContacts(contacts);
            Vector2 dir = contacts[0].point - (new Vector2(transform.position.x, transform.position.y));
            dir = -dir.normalized;
            //dir.y = 0.05f;   // small upward force
            rb.AddForce(dir * force);
        }

        if (life == 0)
        {
            dieSFX.Play();
            alive = false;
        }
    }
コード例 #9
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        ContactPoint2D[] contactPoint = new ContactPoint2D[1];
        collision.GetContacts(contactPoint);

        float contactAngle = Vector2.SignedAngle(Vector2.up, contactPoint[0].normal);

        if (Mathf.Abs(contactAngle) < 65)
        {
            collisionInfo2D.collidersBelow.Add(collision.collider);
        }
        else if (Mathf.Abs(contactAngle) <= 90)
        {
            if (Mathf.Sign(contactAngle) == 1)
            {
                collisionInfo2D.collidersRight.Add(collision.collider);
            }
            else
            {
                collisionInfo2D.collidersLeft.Add(collision.collider);
            }
        }
        else
        {
            collisionInfo2D.collidersAbove.Add(collision.collider);
        }

        collisionInfo2D.Update();
    }
コード例 #10
0
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (leftCollision)
        {
            ContactPoint2D[] contact = new ContactPoint2D[1];
            collision.GetContacts(contact);

            moveSpeed *= collisionSpeedCoefficient;
            float oldMoveAngle = moveAngle - 180f;
            moveAngle = ReflectAngle(moveAngle, contact[0].normal);

            float sparkDuration = 0.3f + ((moveSpeed / initialSpeed) * 0.4f);

            for (int i = 0; i < 2; i++)
            {
                Spark.GetFromPool(sparkPrefab).Initialize(contact[0].point, oldMoveAngle + Random.Range(-5f, 5f),
                                                          sparkDuration,
                                                          (moveSpeed / initialSpeed) * Random.Range(0.5f, 2f), 0.2f, Random.Range(1f, 2f));
            }

            for (int i = 0; i < 2; i++)
            {
                Spark.GetFromPool(sparkPrefab).Initialize(contact[0].point, moveAngle + Random.Range(-5f, 5f),
                                                          sparkDuration,
                                                          (moveSpeed / initialSpeed) * Random.Range(0.5f, 2f), 0.2f, Random.Range(1f, 2f));
            }
        }

        leftCollision = false;
    }
コード例 #11
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("HIT");

        if (collision.gameObject.tag == "Wall")
        {
            ContactPoint2D[] contacts = new ContactPoint2D[5];
            collision.GetContacts(contacts);
            Vector2 colPoint = contacts[0].point;
            Debug.Log(contacts[0].point);
            Vector2 difference = position - colPoint;
            if (Mathf.Abs(difference.x) >= Mathf.Abs(difference.y))
            {
                bounceX();
            }
            else
            {
                bounceY();
            }
        }

        if (collision.gameObject.tag == "Player")
        {
            //
        }
    }
コード例 #12
0
 private void OnCollisionEnter2D(Collision2D other)
 {
     curVelocity = GetComponent <Rigidbody2D>().velocity;
     // if(other.collider.tag == "goals")return;
     // RpcBallBounceAudio();
     if (other.collider.tag == "player")
     {
         //////////////////////////////////////////////
         //////////////////////////////////////////////
         ContactPoint2D[] contacts = new ContactPoint2D[2];
         int numContacts           = other.GetContacts(contacts);
         for (int i = 0; i < numContacts; i++)
         {
             GetComponent <Rigidbody2D>().velocity = new Vector2(curVelocity.x / 3 + ((contacts[i].point - other.gameObject.GetComponent <Rigidbody2D>().position).x * 7f), curVelocity.y);
         }
         if (curVelocity.y <= 0)
         {
             GetComponent <Rigidbody2D>().velocity += new Vector2(0, -1.5f);
             // Debug.Log("Added negative Velocity");
         }
         else
         {
             // Debug.Log("Added Postive Velocity");
             GetComponent <Rigidbody2D>().velocity += new Vector2(0, 1.5f);
         }
         RpcPaddleAudio();
     }
     else
     {
         RpcBallBounceAudio();
     }
 }
コード例 #13
0
 void OnCollisionEnter2D(Collision2D col)
 {
     ContactPoint2D[] contactPoint = new ContactPoint2D[1]; //存储碰撞方向的单位向量
     col.GetContacts(contactPoint);                         //获取碰撞点
     if (contactPoint[0].normal.x < 0 && contactPoint[0].normal.y == 0)
     {
         DirectionC = (int)directions.left;//从左往右
     }
     else if (contactPoint[0].normal.x > 0 && contactPoint[0].normal.y == 0)
     {
         DirectionC = (int)directions.right;//从右往左
     }
     else if (contactPoint[0].normal.y > 0 && contactPoint[0].normal.x == 0)
     {
         DirectionC = (int)directions.up;//从上往下
     }
     else if (contactPoint[0].normal.y < 0 && contactPoint[0].normal.x == 0)
     {
         DirectionC = (int)directions.down;//从下往上
     }
     if (DirectionC == (int)directions.up)
     {
         Ground = true;
         ani.SetBool("jumping", false);
         if (col.gameObject.tag != "plate")
         {
             GameObject.Instantiate(dust, gameObject.transform.position - new Vector3(0, 0.4f, 1), Quaternion.identity);
         }
     }
 }
コード例 #14
0
ファイル: Spatter.cs プロジェクト: nickc01/WeaverCore
        static Vector2 GetSafeContactNormal(Collision2D collision)
        {
            int contacts = collision.GetContacts(contactsBuffer);

            if (contacts >= 1)
            {
                ContactPoint2D contactPoint2D = contactsBuffer[0];
                return(contactPoint2D.normal);

                /*return new Collision2DUtils.Collision2DSafeContact
                 * {
                 *      Point = contactPoint2D.point,
                 *      Normal = contactPoint2D.normal,
                 *      IsLegitimate = true
                 * };*/
            }
            Vector2 b = collision.collider.transform.TransformPoint(collision.collider.offset);
            Vector2 a = collision.otherCollider.transform.TransformPoint(collision.otherCollider.offset);

            /*return new Collision2DUtils.Collision2DSafeContact
             * {
             *      Point = (a + b) * 0.5f,
             *      Normal = (a - b).normalized,
             *      IsLegitimate = false
             * };*/
            return((a - b).normalized);
        }
コード例 #15
0
    protected virtual void OnCollisionEnter2D(Collision2D collision)
    {
        shouldCheck = true;

        //TODO make sure elevation is roughly the same; maybe use ContactFilter2D with useDepth ???
        if (collision.collider.CompareTag("Body") && collision.collider != thisBodyCollider)
        {
            //Check whether collided body is the same team
            Body hitBody = collision.collider.gameObject.GetComponent <Body>();
            if (hitBody && hitBody.team != thisBody.team)
            {
                if (targetColl && collision.collider != targetColl)
                {
                    Physics2D.IgnoreCollision(targetColl, thisCollider, false);
                }
                targetColl = collision.collider;
                target     = targetColl.gameObject;
                targetRB   = target.GetComponent <Rigidbody2D>();

                //Determine the point of contact
                ContactPoint2D[] contactPoints = new ContactPoint2D[1];
                collision.GetContacts(contactPoints);
                ContactPoint2D contact      = contactPoints[0];
                Vector2        contactPoint = contact.point;

                HitCalc(contactPoint, hitBody, collision);
            }
        }
        if (soundbox)
        {
            soundbox.Hit(collision.relativeVelocity.magnitude / 100f);
        }
        // soundbox.Hit(1f);
    }
コード例 #16
0
ファイル: Player.cs プロジェクト: mandarinx/Deflector
        private void OnCollisionEnter2D(Collision2D other)
        {
            if (!activated)
            {
                return;
            }

            if (!LayerMasks.LayerInMask(other.gameObject.layer, hurtBy))
            {
                return;
            }

            int contacts = other.GetContacts(contactPoints);

            if (contacts == 0)
            {
                return;
            }

            hitNormal = Vector2.zero;
            for (int i = 0; i < contacts; ++i)
            {
                hitNormal += contactPoints[i].normal;
            }
            hitNormal /= contacts;
            hitNormal.Normalize();

            Hit();
        }
コード例 #17
0
        protected override void OnCollisionEnter2D(Collision2D collision)
        {
            base.OnCollisionEnter2D(collision);

            Collider2D otherCol         = collision.collider;
            GameObject otherObj         = otherCol.gameObject;
            int        otherLayer       = otherObj.layer;
            string     otherLayerName   = LayerMask.LayerToName(otherLayer);
            Vector3    otherObjPosition = otherObj.transform.position;

            if (string.Compare(otherLayerName, "Default") == 0)
            {
                Debug.Log("Charged into object on Default layer", otherObj);
            }
            else if (otherLayer == WallLayer)
            {
                if (IsCharging)
                {
                    StopCharging(true);
                    int contactCount = collision.GetContacts(contacts);
                    if (contactCount > 0)
                    {
                        wallNormal = contacts[0].normal;
                    }
                }
            }
        }
コード例 #18
0
 // add collision points to list of rays to cast
 void OnCollisionEnter2D(Collision2D collision)
 {
     ContactPoint2D[] contactPoints = new ContactPoint2D[collision.contactCount];
     collision.GetContacts(contactPoints);
     foreach (ContactPoint2D c in contactPoints)
     {
         Vector2 contactVector = c.point - (Vector2)transform.position;
         if (!contactVectors.Contains(contactVector))
         {
             contactVectors.Add(contactVector);
         }
     }
     if (collision.gameObject.CompareTag("Button"))
     {
         Button b = collision.collider.GetComponent <Button>();
         foreach (ContactPoint2D c in contactPoints)
         {
             float angle = Vector2.Angle(c.normal, b.gameObject.transform.up);
             //Debug.Log(angle);
             if (angle <= 45)
             {
                 b.Press();
             }
         }
     }
 }
コード例 #19
0
    private void OnCollisionEnter2D(Collision2D other)
    {
        ContactPoint2D[] contactPoints = new ContactPoint2D[3];
        other.GetContacts(contactPoints);

        foreach (ContactPoint2D contactPoint2D in contactPoints)
        {
            if (!contactPoint2D.rigidbody)
            {
                break;
            }

            if (contactPoint2D.rigidbody.CompareTag("DeadZone") && !godMode)
            {
                playerMovement.CancelJump();
                playerMovement.KillVelocity();
                deaths++;
                GetComponent <PlayerDeath>().Die();
                break;
            }

            if (contactPoint2D.otherCollider.name == "Feet" && contactPoint2D.rigidbody.CompareTag("SafeGround"))
            {
                playerMovement.KillVelocity();
            }
        }
    }
コード例 #20
0
    private void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.gameObject.tag != "Wall")
        {
            return;
        }
        ContactPoint2D[] points = new ContactPoint2D[500];
        collision.GetContacts(points);
        ContactPoint2D?prevP = null;

        foreach (ContactPoint2D p in points)
        {
            if (p.collider == null)
            {
                continue;
            }
            if (prevP != null && Mathf.Abs(prevP.Value.point.y - p.point.y) > 0.1f)
            {
                return;
            }
            prevP = p;
        }
        //Making sure the surface is actually "Under" the player
        if (points[0].point.y - this.transform.position.y < 0 && down)
        {
            return;
        }
        if (points[0].point.y - this.transform.position.y > 0 && !down)
        {
            return;
        }
        //velo = new Vector3(0, 0, 0);
        //this.transform.Translate(-velo * Time.deltaTime);
        grav = new Vector3(0, 0, 0);
    }
コード例 #21
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        _cannotJump = false;

        //Debug.Log("Enter");

        int length = collision.GetContacts(contacts);

        for (int i = 0; i < length; i++)
        {
            accumCollision      += contacts[i].normal * 2;
            accumCollisionCount += 2f;
        }

        normalizedCollision = accumCollision / accumCollisionCount;


        if (collision.collider.gameObject.layer != _vehicleLayer && (collision.collider.gameObject.layer == LayerMask.NameToLayer("Vehicle1") || collision.collider.gameObject.layer == LayerMask.NameToLayer("Vehicle2") || collision.collider.gameObject.layer == LayerMask.NameToLayer("Vehicle3") || collision.collider.gameObject.layer == LayerMask.NameToLayer("Vehicle4")))
        {
            if (collision.relativeVelocity.magnitude > 15)
            {
                _playerController.HealthLoss(collision.relativeVelocity.magnitude * 3f);
            }
        }
    }
コード例 #22
0
    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.tag != "Wall")
        {
            return;
        }
        ContactPoint2D[] points = new ContactPoint2D[500];
        collision.GetContacts(points);
        ContactPoint2D?prevP = null;

        foreach (ContactPoint2D p in points)
        {
            if (p.collider == null)
            {
                continue;
            }
            if (prevP != null && Mathf.Abs(prevP.Value.point.y - p.point.y) > 0.1f)
            {
                return;
            }
            prevP = p;
        }
        if (down)
        {
            grav = new Vector3(0, 1f, 0);
        }
        else
        {
            grav = new Vector3(0, -1f, 0);
        }
    }
コード例 #23
0
    void OnCollisionEnter2D(Collision2D collision)
    {
        Grid grid = tilemap.layoutGrid;
        List <ContactPoint2D> contactList = new List <ContactPoint2D>();
        List <Vector3Int>     processed   = new List <Vector3Int>();

        collision.GetContacts(contactList);
        foreach (ContactPoint2D contactPoint in contactList)
        {
            Vector3Int cell = grid.WorldToCell(contactPoint.point);
            if (cell == new Vector3Int(0, 0, 0))
            {
                continue;
            }
            if (tilemap.GetTile(cell) == null)
            {
                continue;
            }
            if (processed.Contains(cell))
            {
                continue;
            }
            Debug.Log(cell);
            Debug.Log(Vector3.Distance(contactPoint.point, collision.collider.transform.position));
            if (Mathf.Round(Vector3.Distance(contactPoint.point, collision.collider.transform.position)) > 1)
            {
                continue;
            }
            processed.Add(cell);
            BreakBlock(cell);
            GameManager.instance.score += 5 * (gameOverRadiusCurr - gameOverRadius + 1);
        }
    }
コード例 #24
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag(GameConstants.PLAYER))
        {
            // If a player collides with the back of a ramp,
            // they can pass through the ramp.

            // get the contact points between the ramp and the player
            ContactPoint2D[] contacts = new ContactPoint2D[1];
            int numOfContacts         = collision.GetContacts(contacts);

            // Is the player is solid and in contact with the ramp?
            // (if player is not solid, they can pass through the ramp anyway)
            if (collision.gameObject.GetComponent <PlayerController>().IsSolid&& numOfContacts > 0)
            {
                ContactPoint2D contact = contacts[0];
                // Is the contact point above the player?  If so, this
                // indicates that the player is hitting the back of the ramp.
                if (Vector3.Dot(contact.normal, Vector3.up) > 0.5)
                {
                    // so player can pass thru the ramp (which is achieved by
                    // making the ramp collider a trigger)
                    GetComponent <Collider2D>().isTrigger = true;
                }
            }
        }
        else if (collision.gameObject.CompareTag(GameConstants.OBSTACLE))
        {
            // creatures are unaffected by ramps (they always pass thru)
            Physics2D.IgnoreCollision(collision.gameObject.GetComponent <Collider2D>(),
                                      GetComponent <Collider2D>());
        }
    }
コード例 #25
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        ContactPoint2D[] contacts = new ContactPoint2D[1];
        collision.GetContacts(contacts);

        GameObject newGOgbject = Instantiate(gameObjectToInstance, new Vector3(contacts[0].point.x, contacts[0].point.y + 5f, 0), Quaternion.identity, null);
    }
コード例 #26
0
        public void OnCollisionEnter2D(Collision2D collision)
        {
            if (null == node)
            {
                return;
            }

            switch (node.VelocityType)
            {
            case Node2D.MoveType.Vector:
                break;

            default:
                Debug.Log("Error. Bounce steering requires vector velocity");
                return;
            }

            var contacts = new List <ContactPoint2D>();

            collision.GetContacts(contacts);
            foreach (ContactPoint2D contact in contacts)
            {
                var velocity = node.Velocity;
                node.Velocity = Vector2.Reflect(velocity, contact.normal);
            }
        }
コード例 #27
0
    // This function provides a rough estimate of how much impact was involved in a collision.
    // Can be used to figure out if something hit something else hard enough to deal damage etc.
    // WARNING: This is a little rough and has some known issues (i.e. GetContacts appears to be a bit buggy on the Unity side)
    protected float collisionImpactLevel(Collision2D collision)
    {
        int   numContacts      = collision.GetContacts(_maybeContactResults);
        float maxContactImpact = 0;

        // GetContacts probably SHOULDN'T ever return 0, but sometimes it does (a bug maybe?)
        // In that rare case, it's okay to allocate the contact array.
        if (numContacts == 0)
        {
            foreach (ContactPoint2D contact in collision.contacts)
            {
                float contactImpact = Vector2.Dot(contact.relativeVelocity, contact.normal);
                if (contactImpact > maxContactImpact)
                {
                    maxContactImpact = contactImpact;
                }
            }
            return(maxContactImpact);
        }
        for (int i = 0; i < numContacts && i < _maybeContactResults.Length; i++)
        {
            float contactImpact = Vector2.Dot(_maybeContactResults[i].relativeVelocity, _maybeContactResults[i].normal);
            if (contactImpact > maxContactImpact)
            {
                maxContactImpact = contactImpact;
            }
        }
        return(maxContactImpact);
    }
コード例 #28
0
ファイル: Player.cs プロジェクト: GDFauxtrot/161-seasongame
    void OnCollisionEnter2D(Collision2D col)
    {
        #region canJump Flagging

        int contactCount = col.GetContacts(contacts);

        for (int i = 0; i < contactCount; ++i)
        {
            Vector2 norm = contacts[i].normal;

            // Reject empty normals
            if (norm == Vector2.zero)
            {
                continue;
            }

            float colAngle = Mathf.Atan2(norm.y, norm.x) * Mathf.Rad2Deg;

            // Assuming gravity is always "down", valid ground angles are between 45 degree slopes
            if (Mathf.Abs(colAngle - 90) <= 45)
            {
                canJump = true;
                // Did the job, escape early
                break;
            }
        }

        #endregion
    }
コード例 #29
0
    /*
     * public bool HasChanged()
     * {
     *  if (changed)
     *  {
     *      changed = false;
     *      return true;
     *  }
     *
     *  return true;
     * }*/

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Ground")
        {
            Debug.Log("Got " + other.contactCount + " contacts.");
            ContactPoint2D[] contacts = { };
            other.GetContacts(contacts);
            for (int ci = 0; ci < other.contactCount; ci++)
            {
                Debug.Log("Normal: " + other.GetContact(ci).normal.ToString());
                if (other.GetContact(ci).normal == Vector2.up)
                {
                    onGround = true;
                    changed  = true;
                    transform.parent.GetComponent <PlayerBehavior>().GroundUpdate();
                    Debug.Log("On ground.");
                    break;
                }
            }
        }

        /*
         * var normal = other.GetContact(0).normal;
         * if (normal == Vector2.right || normal == Vector2.left) {
         *  rb.AddForce(transform.right * rb.velocity.x, ForceMode2D.Force);
         * }*/
    }
コード例 #30
0
ファイル: Ship.cs プロジェクト: Xenation/Ludum-Dare-41
 protected void OnCollisionEnter2D(Collision2D collision)
 {
     if (gameObject.layer == LayerUtils.Player)
     {
         if (collision.gameObject.layer == LayerUtils.EnemyProjectile)
         {
             Projectile projectile = collision.gameObject.GetComponent <Projectile>();
             ReceiveDamage(projectile.damage);
             projectile.Kill();
         }
     }
     else if (gameObject.layer == LayerUtils.Enemy)
     {
         if (collision.gameObject.layer == LayerUtils.PlayerProjectile)
         {
             Projectile       projectile = collision.gameObject.GetComponent <Projectile>();
             ContactPoint2D[] contacts   = new ContactPoint2D[1];
             if (collision.GetContacts(contacts) != 0)
             {
                 Instantiate(Resources.Load("Prefabs/Explosion"), contacts[0].point, Quaternion.identity);
             }
             ReceiveDamage(projectile.damage);
             projectile.Kill();
         }
     }
 }