コード例 #1
0
        void OnCollisionEnter2D(Collision2D other)
        {
            //Input Direction for the reflect  function
            Vector3 inDirection = rigid.velocity.normalized;
            //contact information with collision
            ContactPoint2D contact = other.contacts[0];
            //Input normal of the contact,s surface
            Vector3 inNormal = contact.normal;
            //Reflection vector pointing in the direction you want to go
            Vector3 reflect = Vector3.Reflect(inDirection, inNormal);
            //Newly calculated force from reflection
            Vector3 newForce = reflect * rigid.velocity.magnitude;

            //Replace velocity on object with reflection direction
            rigid.velocity = newForce;
        }
コード例 #2
0
    protected virtual void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.contacts.Length > 0 && collision.gameObject.tag == "Jumpable")
        {
            ContactPoint2D contact = collision.contacts[0];

            if (Vector3.Dot(contact.normal, Vector3.up) > 0.5)
            {
                isOnJumpingSurface = true;
            }
            else
            {
                isOnJumpingSurface = false;
            }
        }
    }
コード例 #3
0
    void GetGroundPoint(List <ContactPoint2D> contacts, out ContactPoint2D flattestContactPoint)
    {
        flattestContactPoint = new ContactPoint2D();
        float bestDot = -1;

        foreach (ContactPoint2D cp in contacts)
        {
            Debug.DrawRay(cp.point, cp.normal * 0.2f, Color.white, 0f, false);
            float newDot = Vector2.Dot(cp.normal, Vector2.up);
            if (newDot > bestDot && newDot > 0f)
            {
                bestDot = newDot;
                flattestContactPoint = cp;
            }
        }
    }
コード例 #4
0
    //cuando el jugador salte sobre este objeto, lo destruirá
    private void OnCollisionEnter2D(Collision2D other)
    {
        //el jugador tiene que tener un componente PlayerMovement (para que solo pueda ser el jugador)
        if (other.gameObject.GetComponent <PlayerMovement>())
        {
            //buscamos la normal y calculamos el ángulo entre la normal y el vector Up
            ContactPoint2D contact = other.contacts[0];
            float          angle   = Vector2.Angle(contact.normal, transform.up);

            //si el ángulo es de unos 180º (el jugador cae verticalmente), destruye al enemigo
            if (Mathf.Approximately(angle, 180))
            {
                Destroy(this.gameObject);
            }
        }
    }
コード例 #5
0
    protected void OnTriggerEnter2D(Collider2D collision)
    {
        Collider2D collider = collision.GetComponent <Collider2D>();

        ContactPoint2D[] contactPoint = new ContactPoint2D[1];
        collision.GetContacts(contactPoint);
        Vector3 center = collider.bounds.center;

        //bool right = contactPoint[0].point.x > center.x;
        bool top = contactPoint[0].point.y > center.y;

        if (this.grounded && top)
        {
            this.isAlive = false;
        }
    }
コード例 #6
0
        /// <summary>
        /// Sets all the structs fields, based on the callback ("enter" or "stay") and the 2D contact.
        /// </summary>
        public void Set(bool firstContact, ContactPoint2D contact)
        {
            this.firstContact = firstContact;
            this.collider2D   = contact.collider;
            this.point        = contact.point;
            this.normal       = contact.normal;
            this.gameObject   = this.collider2D.gameObject;

            Rigidbody2D contactRigidbody = this.collider2D.attachedRigidbody;

            if (this.isRigidbody = contactRigidbody != null)
            {
                this.isKinematicRigidbody = contactRigidbody.isKinematic;
                this.pointVelocity        = contactRigidbody.GetPointVelocity(this.point);
            }
        }
コード例 #7
0
ファイル: PlatformCatcher.cs プロジェクト: dek0058/Dark-Tower
        private void CheckRigidbodyContacts(Rigidbody2D _rigidbody)
        {
            int contactCount = _rigidbody.GetContacts(contact_filter, m_contact_points);

            for (int j = 0; j < contactCount; j++)
            {
                ContactPoint2D contactPoint2D   = m_contact_points[j];
                Rigidbody2D    contactRigidbody = contactPoint2D.rigidbody == _rigidbody ? contactPoint2D.otherRigidbody : contactPoint2D.rigidbody;
                int            listIndex        = -1;

                for (int k = 0; k < m_caught_objects.Count; k++)
                {
                    if (contactRigidbody == m_caught_objects[k].rigidbody)
                    {
                        listIndex = k;
                        break;
                    }
                }

                if (listIndex == -1)
                {
                    if (contactRigidbody != null)
                    {
                        if (contactRigidbody.bodyType != RigidbodyType2D.Static && contactRigidbody != platform_rigidbody)
                        {
                            float dot = Vector2.Dot(contactPoint2D.normal, Vector2.down);
                            if (dot > 0.8f)
                            {
                                CaughtObject newCaughtObject = new CaughtObject {
                                    rigidbody          = contactRigidbody,
                                    character          = contactRigidbody.GetComponent <CharacterController2D>(),
                                    collider           = contactRigidbody.GetComponent <Collider2D>(),
                                    in_contact         = true,
                                    checked_this_frame = false
                                };

                                m_caught_objects.Add(newCaughtObject);
                            }
                        }
                    }
                }
                else
                {
                    m_caught_objects[listIndex].in_contact = true;
                }
            }
        }
コード例 #8
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (GetComponentInChildren <ParticleSystem>() != null)
        {
            GetComponentInChildren <ParticleSystem>().Play();
        }
        noCollision = false;

        InstantiateObject inst = GetComponent <InstantiateObject>();

        if (inst != null)
        {
            if (collision.gameObject.GetComponent <TilemapCollider2D>() != null)
            {
                ContactPoint2D[] contact = new ContactPoint2D[1];
                collision.GetContacts(contact);

                if (contact[0].normal.y > 0)
                {
                    Vector2 hitPoint = new Vector2(contact[0].point.x, contact[0].point.y + 0.25f);
                    if (hitPoint.y < transform.position.y)
                    {
                        //Instantiate(explosion, new Vector3(hitPoint.x, hitPoint.y, 0), Quaternion.identity);
                        inst.Instantiate(hitPoint);
                        Invoke("DestroyThis", 0.4f);
                    }
                }
            }

            else
            {
                ContactPoint2D[] contact = new ContactPoint2D[1];
                collision.GetContacts(contact);

                if (contact[0].normal.y > 0)
                {
                    inst.Instantiate(new Vector2(contact[0].point.x, contact[0].point.y + 0.4f));
                    Invoke("DestroyThis", 0.4f);
                }
            }
        }

        else
        {
            Destroy(gameObject);
        }
    }
コード例 #9
0
    private void updatePlayerRotToSlope(Collision2D collision)
    {
        // exit if not ground
        if (collision.gameObject.layer != groundLayerIndex)
        {
            return;
        }
        Debug.Log(" is ground ");

        //ContactPoint2D contact = new ContactPoint2D();
        ContactPoint2D[] contacts = {};
        contacts = collision.contacts;
        if (contacts.Length == 0)
        {
            return;
        }
        // todo : use the normal of segment linking both contact points
        ContactPoint2D contact = contacts[0];

        Debug.Log(" ground point found : n_contacts is " + contacts.Length);

        Vector2 ground_N = contact.normal;
        Vector2 up       = transform.up;

        Vector3 rayOrigin = this.transform.position;
        float   rayLength = 10f;

        Debug.DrawRay(rayOrigin, new Vector3(ground_N.x, ground_N.y, 0) * rayLength, Color.red);

        // Nvector dot UPvector / Nnorm * UPnorm
        //float acos_val = Vector3.Dot( ground_N, up ) / (ground_N.magnitude * up.magnitude );
        //float angle = Mathf.Acos(acos_val);

        // TODO : 1 bug with 180d angle
        float angle2 = Vector2.Angle(ground_N, up);

        if (angle2 == 0f)
        {
            Debug.Log("transfo ok");
            hasRightZRotation = true;
            return;
        }

        hasRightZRotation = false;
        transform.Rotate(0f, 0f, angle2, Space.Self);
        Debug.Log("angle2 is " + angle2);
    }
コード例 #10
0
ファイル: PlayerScript.cs プロジェクト: rakibj/Death-Run
 private void OnCollisionEnter2D(Collision2D collision)
 {
     if (collision.gameObject.tag == "Obstacles" ||
         collision.gameObject.tag == "Spikes")
     {
         if (collision.gameObject.tag == "Obstacles")
         {
             particleEffects.ShowBloodObstacleEffect(transform);
         }
         else
         {
             particleEffects.ShowBloodSpikeEffect(transform);
         }
         GameObject destroyed;
         destroyed = Instantiate(destroyedPlayer as GameObject);
         destroyed.transform.position = this.gameObject.transform.position;
         if (!GameManager.showAdScreen && GameManager.elligibleForRevive)
         {
             GameManager.showAdScreen = true;
             GameManager.rewardUsed   = 1;
         }
         else if (!GameManager.elligibleForRevive)
         {
             GameManager.showAdScreen = false;
             GameManager.playerDead   = true;
         }
         ContactPoint2D contact = collision.contacts[0];
         Vector3        dir     = contact.point - new Vector2(destroyed.transform.position.x, destroyed.transform.position.y);
         dir = -dir.normalized;
         Rigidbody2D[] rgb = destroyed.GetComponentsInChildren <Rigidbody2D>();
         foreach (Rigidbody2D r in rgb)
         {
             if (collision.gameObject.tag == "Obstacles")
             {
                 FindObjectOfType <AudioManager>().Play("saw death");
                 r.AddForce(new Vector2(destroySpeedOnObstacle, destroySpeedOnObstacle), ForceMode2D.Impulse);
             }
             if (collision.gameObject.tag == "Spikes")
             {
                 FindObjectOfType <AudioManager>().Play("spike death");
                 r.AddForce(new Vector2(destroySpeedOnSpike, destroySpeedOnSpike), ForceMode2D.Impulse);
             }
         }
         //GameManager.showAdScreen = true;
         Destroy(this.gameObject);
     }
 }
コード例 #11
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (!gameOver)
        {
            onSurface = true;
            if (collision.gameObject.CompareTag("Border"))
            {
                print("hit border");
                ContactPoint2D contact  = collision.contacts[0];
                Quaternion     rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
                Vector3        position = contact.point;
                EggBreak(position, rotation);
            }
            else if (!collision.gameObject.CompareTag("Bubble"))
            {
                if (collision.relativeVelocity.magnitude > breakVel)
                {
                    ContactPoint2D contact  = collision.contacts[0];
                    Quaternion     rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
                    Vector3        position = contact.point;
                    EggBreak(position, rotation);
                }
                else if (collision.relativeVelocity.magnitude > crackVel)
                {
                    if (!isCracked)
                    {
                        isCracked        = true;
                        eggSprite.sprite = angryCrackedEggSprite;
                    }
                    else
                    {
                        ContactPoint2D contact  = collision.contacts[0];
                        Quaternion     rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
                        Vector3        position = contact.point;
                        EggBreak(position, rotation);
                    }
                }
            }

            else
            {
                trail.SpawnDot(1);
                blower.SetBubbleNum(false);
                Destroy(collision.gameObject);
            }
        }
    }
コード例 #12
0
    public bool isNormalForceInDirection(int direction)          // 1 is up, 2 is right, 3 is down, 4 is left
    {
        ContactPoint2D[] contactPoints = new ContactPoint2D[20]; // this 20 is an intentional over estimate
        int numOfContacts = rb.GetContacts(contactPoints);

        if (direction == 1)
        {
            for (int i = 0; i < numOfContacts; i++)
            {
                if (contactPoints[i].normal.y >= 0.7f) // if on any contact points the y axis is experienceing an upwards normal force, ie it is on top of an object
                {
                    return(true);
                }
            }
        }
        else if (direction == 2)
        {
            for (int i = 0; i < numOfContacts; i++)
            {
                if (contactPoints[i].normal.x >= 0.7f)
                {
                    return(true);
                }
            }
        }
        else if (direction == 3)
        {
            for (int i = 0; i < numOfContacts; i++)
            {
                if (contactPoints[i].normal.y <= -0.7f)
                {
                    return(true);
                }
            }
        }
        else if (direction == 4)
        {
            for (int i = 0; i < numOfContacts; i++)
            {
                if (contactPoints[i].normal.x <= -0.7f)
                {
                    return(true);
                }
            }
        }
        return(false);
    }
コード例 #13
0
        void OnCollisionEnter2D(Collision2D other)
        {
            //grab contact point of collision
            ContactPoint2D contact = other.contacts[0];
            //calculate the reflection point of the ball using velocity & contact normal
            Vector3 reflect = Vector3.Reflect(velocity, contact.normal);

            //claculate new velocity from reflection multiply by the same speed (velocity.magnitude)
            velocity = reflect.normalized * velocity.magnitude;

            // If I hit a block
            if (other.gameObject.CompareTag("Blocks"))
            {
                // Deactivate it
                other.gameObject.SetActive(false);
            }
        }
コード例 #14
0
ファイル: Richochet.cs プロジェクト: zeburgana/gamedevexe
    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.transform.tag == "Bouncy")
        {
            // get the point of contact
            ContactPoint2D contact = collision.contacts[0];

            // reflect our old velocity off the contact point's normal vector
            Vector3 reflectedVelocity = Vector3.Reflect(oldVelocity, contact.normal);

            // assign the reflected velocity back to the rigidbody
            rigidbody.velocity = reflectedVelocity;
            // rotate the object by the same ammount we changed its velocity
            Quaternion rotation = Quaternion.FromToRotation(oldVelocity, reflectedVelocity);
            transform.rotation = rotation * transform.rotation;
        }
    }
コード例 #15
0
    /// <summary>
    /// Fixes the collision
    /// </summary>
    /// <param name="coll"></param>
    /// <returns></returns>
    bool fixingCollision(Collision2D coll)
    {
        ContactPoint2D[] results;
        results = new ContactPoint2D[5];
        coll.GetContacts(results);
        //print(results[0].point.x);

        if (Mathf.Abs(results[0].point.x) > 5.7 && Mathf.Abs(results[0].point.x) < 5.8)
        {
            return(true);
        }

        else
        {
            return(false);
        }
    }
コード例 #16
0
    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Hazard" || col.gameObject.tag == "Enemy")
        {
            contact   = col.contacts [0];
            timeHit   = Time.time;
            Hit       = true;
            noControl = true;
            StartCoroutine("Blink");

            //Allow player to pass thorugh enemies
            foreach (GameObject enemy in enemies)
            {
                Physics2D.IgnoreCollision(this.GetComponent <Collider2D>(), enemy.GetComponent <Collider2D>(), true);
            }
        }
    }
コード例 #17
0
 private void OnCollisionEnter2D(Collision2D collision)
 {
     if (type == NodeType.Leaf && collision.transform.tag == "ball")
     {
         // 碰撞点
         ContactPoint2D contact  = collision.contacts[0];
         Quaternion     rot      = Quaternion.FromToRotation(Vector3.up, contact.normal);
         Vector3        hitPoint = contact.point;
         // 碰撞点指向圆心的向量
         Vector3 normal = Vector3.Normalize(transform.position - hitPoint);
         transform.parent.GetComponent <Rope>().AddForce(normal * 1000);
     }
     else if (type == NodeType.Mid && collision.transform.tag == "ball")
     {
         transform.parent.GetComponent <Rope>().BreakTheRope(Int32.Parse(transform.name));
     }
 }
コード例 #18
0
    //                       _         _
    //sometimes it is needed  \_(-_-)_/
    void OnCollisionStay2D(Collision2D collider)
    {
        if (!isGrounded)
        {
            ContactPoint2D[] cpa = new ContactPoint2D[collider.contactCount];
            collider.GetContacts(cpa);

            if (collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
            {
                if (Array.Exists <ContactPoint2D>(cpa, (ContactPoint2D x) => x.point.y < gameObject.transform.position.y))
                {
                    // ...then he might jump again
                    isGrounded = true;
                }
            }
        }
    }
コード例 #19
0
ファイル: ExplosionScript.cs プロジェクト: maximtsai/AGDAGame
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.contacts.Length > 0)
        {
            ContactPoint2D contact = collision.contacts[0];
            // compare relative velocity to collision normal - so we don't explode from a fast but gentle glancing collision

            float velocityAlongCollisionNormal = Mathf.Abs(Vector2.Dot(contact.normal, collision.relativeVelocity));

            if (velocityAlongCollisionNormal > detonationImpactVelocity)
            {
            }
        }
        if (Time.time > startTime + detonationDelay)
        {
        }
    }
コード例 #20
0
 private void OnCollisionEnter2D(Collision2D collision)
 {
     if (collision.gameObject.tag == "Wall")
     {
         ContactPoint2D contactPoint = collision.contacts[0];
         Vector2        newDir       = Vector2.zero;
         Vector2        curDir       = transform.TransformDirection(Vector2.right);
         newDir = Vector2.Reflect(curDir, contactPoint.normal);
         Quaternion rotation = Quaternion.FromToRotation(Vector2.right, newDir);
         transform.rotation = rotation;
         if (speed > minSpeed)
         {
             speed -= speedDownPerCollision;
         }
         rigid.velocity = transform.TransformDirection(1, 0, 0).normalized *speed *Time.deltaTime;
     }
 }
コード例 #21
0
ファイル: detectCollision.cs プロジェクト: tranecheg/GoDucky
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Knife"))
        {
            StartGame.isStart = false;
            Destroy(collision.transform.parent.gameObject);
            rend.color = deathColor;

            ContactPoint2D contact = collision.contacts[0];
            Vector3        pos     = contact.point;
            GameObject     exp     = Instantiate(explosion, pos, Quaternion.identity);
            Destroy(exp, 1);
            lose.Play();

            panelLose.SetActive(true);
        }
    }
コード例 #22
0
 void OnCollisionEnter2D(Collision2D col)
 {
     if (col.gameObject.layer == chapsLayer)
     {
         GameController.ChapCollected.Invoke(col.gameObject, col);
     }
     else
     {
         ContactPoint2D contact        = col.contacts[0];
         Vector2        pos            = contact.point;
         float          y_contact_diff = gameObject.transform.position.y - pos.y;
         if (y_contact_diff > 0.5f)
         {
             GameController.ComboBroken.Invoke();
         }
     }
 }
コード例 #23
0
    void OnCollisionEnter2D(Collision2D coll)
    {
        ContactPoint2D contact = coll.contacts [0];

        Debug.Log("Hit!");
        //Debug.DrawRay (contact.point, contact.normal, Color.white);
        // play the reflect sound
        //if (coll.transform.tag != "Player") {
        //myAudioSource.PlayOneShot (reflectSound);
        //}
        Vector2 newDirection = Vector2.Reflect(transform.up, contact.normal);

        transform.up         = newDirection.normalized;
        myRigidbody.velocity = newDirection.normalized * initialVelocity;

        // draw a special kind of light at the contact point
    }
コード例 #24
0
    private void OnCollisionStay2D(Collision2D collision)
    {
        if (attachedObject == null && collision.gameObject.GetComponent <AttachableObject>() != null && attachCooldown < 0.001f)
        {
            AttachableObject collidedObject = collision.gameObject.GetComponent <AttachableObject>();
            attachedObject = collidedObject;
            collidedObject.AddAttacher(gameObject);
            transform.SetParent(collidedObject.transform);

            ContactPoint2D contact   = collision.contacts[0];
            Vector2        direction = new Vector2(contact.point.x - collision.gameObject.transform.position.x, contact.point.y - collision.gameObject.transform.position.y);
            float          angle     = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
            Rigidbody2D r2D = gameObject.GetComponent <Rigidbody2D>();
            r2D.simulated = false;
        }
    }
コード例 #25
0
    public static int constructor(IntPtr l)
    {
        int result;

        try
        {
            ContactPoint2D contactPoint2D = default(ContactPoint2D);
            LuaObject.pushValue(l, true);
            LuaObject.pushValue(l, contactPoint2D);
            result = 2;
        }
        catch (Exception e)
        {
            result = LuaObject.error(l, e);
        }
        return(result);
    }
コード例 #26
0
 void OnCollisionEnter2D(Collision2D collider)
 {
     ContactPoint2D[] cpa = new ContactPoint2D[collider.contactCount];
     collider.GetContacts(cpa);
     // If player is on the ground...
     if (collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
     {
         if (Array.Exists <ContactPoint2D>(cpa, (ContactPoint2D x) => x.point.y < gameObject.transform.position.y))
         {
             // ...then he might jump again
             isGrounded = true;
             /* Reset rising up variables */
             isJumping       = false;
             jumpTimeCounter = 0f;
         }
     }
 }
コード例 #27
0
ファイル: ButtonRelated.cs プロジェクト: adi11151/syporio
 private void OnCollisionEnter2D(Collision2D collision)
 {
     if ((_buttonPushed == false) && (collision.gameObject.tag == "Player"))
     //Physics.IgnoreCollision(collider1: collision, collider2: this )
     {
         if (_platformUp == false)
         {
             ContactPoint2D contact = collision.contacts[0];
             if (contact.point.y > transform.position.y + 0.5)
             {
                 _buttonPushed = true;
                 StartCoroutine(ButtonPushed());
                 _buttonPushed = false;
             }
         }
     }
 }
コード例 #28
0
        public static Surface SurfaceFromCollision2D(Collision2D collision)
        {
            int enemiesLayer = LayerMask.NameToLayer("Enemies");

            if (collision.collider.gameObject.layer == enemiesLayer)
            {
                Debug.Log("Touch enemy");
                return(Surface.Enemy);
            }
            else
            {
                ContactPoint2D[] contact = new ContactPoint2D[2];
                collision.GetContacts(contact);

                return(SurfaceDetector.SurfaceFromNormal(contact [0].normal));
            }
        }
コード例 #29
0
    public bool IsOnTheGround()
    {
        ContactPoint2D[] contacts    = new ContactPoint2D[5];
        int contactCount             = _rigidbody2d.GetContacts(contacts);
        int whyTheHellINeedThisCount = contactCount;

        foreach (ContactPoint2D contact in contacts)
        {
            if (contact.normal.y >= 0.9f)
            {
                contactCount = whyTheHellINeedThisCount;
                return(true);
            }
        }
        contactCount = whyTheHellINeedThisCount;
        return(false);
    }
コード例 #30
0
    private void GroundCheck(Collision2D other)
    {
        var contacts = new ContactPoint2D[other.contactCount];

        other.GetContacts(contacts);

        foreach (var c in contacts)
        {
            if (Vector2.Angle(c.normal, gravity) >= 120)
            {
                grounded     = true;
                groundNormal = c.normal;
                return;
            }
        }
        grounded = false;
    }