コード例 #1
0
 private void OnCollisionExit2D(Collision2D collision)
 {
     if (collision?.contactCount > 0)
     {
         if (collision?.GetContact(0).normal.normalized == Vector2.up && ground == (ground | (1 << collision.gameObject.layer)))
         {
             grounded = false;
         }
     }
 }
コード例 #2
0
        private void OnCollisionEnter2D(Collision2D other)
        {
            if (!other.collider.CompareTag("Player"))
            {
                return;
            }
            if (Mathf.Abs(other.relativeVelocity.y) < 0.5f)
            {
                return;
            }

            // If collision was from not the top, dont damage the object
            var contact = other.GetContact(0);

            if (Vector3.Dot(contact.normal, Vector3.down) <= 0.7f)
            {
                return;
            }

            DamageObject();
        }
コード例 #3
0
 private void OnCollisionEnter2D(Collision2D other)
 {
     if (other.transform.tag == "Ground")
     {
         animator.SetBool("Jump", false);
     }
     if (other.transform.tag == "Spike")
     {
         health = 0f;
     }
     else if (other.transform.tag == "Enemy")
     {
         float   pushForce      = other.gameObject.GetComponent <Enemy>().GetForce();
         float   damageReceived = other.gameObject.GetComponent <Enemy>().GetDamage();
         Vector2 myTransform    = new Vector2(transform.position.x, transform.position.y);
         Vector2 dir            = other.GetContact(0).point - myTransform;
         dir = -dir.normalized;
         rigidbody2D.AddForce(dir * pushForce);
         health -= damageReceived;
     }
 }
コード例 #4
0
ファイル: Draggable.cs プロジェクト: oPeries/Crimey_Boyz
    /// <summary>
    /// Check if the draggable is being dragged into a position that it won't fit in
    /// </summary>
    /// <param name="collision"> The object the draggable is being dragged into </param>
    protected virtual void OnCollisionEnter2D(Collision2D collision)
    {
        //should do a check if the object is static

        if (!isEntered)
        {
            Debug.Log("RECALC");

            Vector2 currentPos  = gameObject.transform.position;
            Vector2 collidedPos = collision.GetContact(0).point;
            //TODO: CLEANUP MATHS SO IT WORKS IN ALL DIRECTIONS
            enteredPoint = currentPos + (currentPos - collidedPos) * 0.05f;
        }

        HandleEnteredCollisions(true);

        //may need to remove depending on implementation
        //freeze rotation and turn red
        gameObject.transform.rotation = new Quaternion(0, 0, 0, 0);
        gameObject.GetComponentsInChildren <Renderer>()[0].material.SetColor("_Color", Color.red);
    }
コード例 #5
0
    private void OnCollisionEnter2D(Collision2D other)
    {
        //This is for when the hammer touch the ground.
        //particles emit out into the world and if it touches an enemy then they will take half damage

        //ContactPoint2D contact = other.GetContact(0);
        //Debug.Log(contact.otherCollider.name + "hit " + contact.collider.name);
        ContactPoint2D contact = other.GetContact(0);

        if (contact.collider.tag == "Hammer")
        {
            hammer = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren <Hammer>();
            Instantiate(hurt, this.transform.position, this.transform.rotation);

            health -= hammer.strength;

            AudioManager.instance.PlaySound("Slime_Hurt");
        }

        if (contact.collider.tag == "Player")
        {
            HurtPrincess();
            player.health -= eDamage;
        }
        if (contact.collider.tag == "Special")
        {
            Debug.Log("Yay");
        }
        if (contact.collider.tag == "Shield")
        {
            if (moveRight)
            {
                moveRight = false;
            }
            else
            {
                moveRight = true;
            }
        }
    }
コード例 #6
0
    // IMPORTANT: What I'm trying to do here is to just know when the collider is hitting the ground (meaning the tag/layer is "Ground" and the normal surface is Vector2.up).
    // Obviously, because Unity is f****** retarded so this little simple task is impossible.
    // Why I was trying to do this in the first place?
    // For example, I may have a grenade that bounces off the wall but when hit an enemy then get stuck to it at a "correct" and "precise" position.
    // Or I can have a molotov that bounces around walls but explode when hit the ground (doesn't count the roof or the diagonal tiles).
    // Or literally right this instance, I'm trying to have dropped guns to bounce back when hitting the wall but stop moving and change their bodyType when hit the ground.
    // Another example I can give is when I shoot a projectile and it hit a wall, I want the particle effect's rotation to be like the collided surface's normal.
    // So as anyone can see (why did I talk to myself?), the most basic and simple task is literally impossible for Unity. God, I hate it so much.
    //  ---------------------------------------
    // I tried to use ContactPoint2D but:
    //  - Sometimes it wasn't correct (the normal and the point). It's also pretty limited what you can do with it.
    //  - The collision.contacts array always has several contact points (when I tested it had 4). Don't ask me why it is and which contact should I use.
    //  - All the OnCollisionX2D always get called after Unity handles its collision so I can't get the correct position or stop it before it bounces back.
    // I tried to use FixedUpdate (or yield return new WaitForFixedUpdates() in coroutine) and manually cast the box.
    // It worked in some instances but overall it wasn't great:
    //  - What should the size.x be? Maybe it should be less than the object's bounds but sometimes when the object moves at a high speed a large chunk of it will be inside walls.
    //  - What should the size.y be? Maybe it should be extremely small but then sometimes there are situations where the box is too deep in the ground and you have custom physics material.
    // Unity can't understand that anybody needs the collision to happen differently on each dir/axis.
    // Another thing that Unity also f*** up is the ability to be triggered to some layers but normal to other layers.
    // Even the idea of splitting stuff into trigger and non-trigger is also pretty stupid.
    // In conclusion, Unity's collision system is quite limited, useless, and its API is f****** retarded. I probably should make my own physics system soon.
    private void OnCollisionEnter2D(Collision2D collision)
    {
        ContactPoint2D contact = collision.GetContact(0);

        if (contact.normal == Vector2.up && contact.collider.CompareTag("Ground"))
        {
            trigger.hitGroundPos = transform.position;
            trigger.textboxType  = TextboxType.Weapon;
            rb.velocity          = Vector2.zero;
            rb.bodyType          = RigidbodyType2D.Kinematic;

            if (moveUpAndDownWhenDrop)
            {
                isMoving              = true;
                trigger.hitGroundPos += new Vector3(0, halfDistance);
                StartCoroutine(UpAndDown(halfDistance, trigger.hitGroundPos.y));

                System.Collections.IEnumerator UpAndDown(float halfDistance, float center)
                {
                    yield return(new WaitForSeconds(waitTime.randomValue));

                    Vector2 dir = Vector2.up;

                    while (isMoving)
                    {
                        if (transform.position.y >= center + halfDistance)
                        {
                            dir = Vector2.down;
                        }
                        else if (transform.position.y <= center - halfDistance)
                        {
                            dir = Vector2.up;
                        }
                        rb.velocity = dir * speed;
                        yield return(null);
                    }
                }
            }
        }
    }
コード例 #7
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (tag == "servant" && collision.collider.tag == "doorTile")
        {
            Debug.Log("open door");
            var doorTileMap = collision.collider.gameObject.GetComponent <Tilemap>();
            var contact     = collision.GetContact(0).point;
            var pos         = tileUtility.getAvatarPosInTilemap(2 * new Vector3(contact.x, contact.y) - transform.position);
            if (doorTileMap.GetTile(pos) == unpassTile_verti)
            {
                RoomPos = pos;
                if (tileUtility.changeToReplaceTile(doorTileMap, pos, passTile_verti))
                {
                    collision.collider.gameObject.GetComponent <CompositeCollider2D>().isTrigger = true;
                }
            }
            if (doorTileMap.GetTile(pos) == unpassTile_hori)
            {
                RoomPos = pos;
                if (tileUtility.changeToReplaceTile(doorTileMap, pos, passTile_hori))
                {
                    collision.collider.gameObject.GetComponent <CompositeCollider2D>().isTrigger = true;
                }
            }
        }

        if (playerController.attatchTo == gameObject)
        {
            if (tag == "fighter" && (collision.collider.tag == "boss" || collision.collider.tag == "servant" || collision.collider.tag == "fighter"))
            {
                Debug.Log("fighter  kill " + gameObject.tag);
                Destroy(collision.collider.gameObject);
                release();
            }
        }
        if (tag == "fighter" && collision.collider.tag == "Player" && playerController.attatchTo != gameObject)
        {
            GameObject.FindObjectOfType <ObveserController>().Lose();
        }
    }
コード例 #8
0
ファイル: DungeonPits.cs プロジェクト: m7rk/ld47
    public void OnCollisionEnter2D(Collision2D c)
    {
        if (c.transform.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            var tilemap = GetComponent <Tilemap>();
            var player  = c.transform.GetComponent <Player>();



            string     tileType   = "";
            Vector3Int tileCenter = Vector3Int.zero;

            for (int i = 0; i != c.contactCount; ++i)
            {
                var center = tilemap.layoutGrid.WorldToCell(c.GetContact(i).point + player.lastVelocity.normalized * 0.1f);
                var tile   = tilemap.GetTile(center);

                if (tile != null)
                {
                    tileType   = tile.name;
                    tileCenter = center;
                    break;
                }
            }

            // ??? this happens sometiems
            if (tileType == "")
            {
                return;
            }

            if (tileType.Contains("PIT"))
            {
                spawnPos = this.transform.position + new Vector3(tileCenter.x + 0.5f, tileCenter.y + 0.5f, 0);
                player.FallIntoPit(spawnPos);
                FindObjectOfType <EnvSounds>().playFallDown();
                makePitPrefab();
            }
        }
    }
コード例 #9
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (!attachedToPaddle)
        {
            if (collision.gameObject == PaddleManager.Instance.currentPaddle)
            {
                // Check if ball needs to attach to magnet paddle
                if (!detachingFromPaddle && PaddleManager.Instance.currentType == PaddleType.Magnet)
                {
                    AttachedByMagnet = true;
                    AttachToPaddle();
                }
                // Calculate paddle bounce
                else
                {
                    float paddleX     = collision.collider.transform.position.x;
                    float paddleWidth = collision.collider.bounds.size.x;
                    float intersectX  = collision.GetContact(0).point.x;

                    // Get X position of ball intersection relative to the paddle
                    float relativeIntersectX = (intersectX - paddleX);
                    // Normalize the X position; make it fall between -1 and 1
                    float normalizedRelativeIntersectionX = (relativeIntersectX / (paddleWidth / 2));
                    // Calculate the bounce angle using the normalized X and the max bounce angle in radians
                    float bounceAngle = normalizedRelativeIntersectionX * maxPaddleBounceAngle;

                    // Calculate the direction using the appropriate X and Y ratio
                    Vector2 newDirection = new Vector2(Mathf.Sin(bounceAngle), Mathf.Cos(bounceAngle));
                    ballBody.velocity = speed * newDirection;

                    hitMultiplier = 1;
                }
            }
            else if (collision.gameObject.CompareTag("Block"))
            {
                ScoreManager.Instance.AddPoints(ScoreAction.BrickHit, hitMultiplier);
                hitMultiplier++;
            }
        }
    }
コード例 #10
0
    private void OnCollisionStay2D(Collision2D collision)
    {
        // collision with enemy
        if (collision.gameObject.layer == 10 && canTakeDamage)
        {
            StartCoroutine("takeDamage");
        }
        // collision with floors or fake floors
        if (collision.gameObject.layer == 8 || collision.gameObject.layer == 15)
        {
            RaycastHit2D hit = Physics2D.Raycast(collision.GetContact(0).point, (Vector2)collision.transform.position - collision.GetContact(0).point);

            float y     = hit.point.y - hit.transform.position.y;
            float limit = (float)collision.transform.lossyScale.y * 0.95f / 2;
            if (y >= limit)
            { // top
                this.isJumping  = false;
                this.isGrounded = true;
                this.canDash    = true;
            }
            else if (y <= -limit)
            { // bottom
            }
            else
            { // side
                if (hit.point.x > hit.transform.position.x)
                {
                    sideLeft = false;
                }
                else
                {
                    sideLeft = true;
                }
                this.isSide     = true;
                this.isJumping  = false;
                this.isGrounded = true;
                this.canDash    = true;
            }
        }
    }
コード例 #11
0
        void OnCollisionEnter2D(Collision2D collision)
        {
            Vector2 normal = collision.GetContact(0).normal;

            if (collision.gameObject.tag == "Monster")
            {
                //turn around
                if (SameSign(collision.gameObject.GetComponent <ICreature>().HorizontalMoveDirection, HorizontalMoveDirection) || collision.gameObject.GetComponent <ICreature>().HorizontalMoveDirection == 0)
                {
                    rigidBody.velocity      = new Vector2(0f, rigidBody.velocity.y);
                    HorizontalMoveDirection = -HorizontalMoveDirection;
                }
            }

            //collision with the player (when the player is not bouncing)
            if (collision.gameObject.tag == "Player" && normal != Vector2.down)
            {
                //turn around
                rigidBody.velocity      = new Vector2(0f, rigidBody.velocity.y);
                HorizontalMoveDirection = -HorizontalMoveDirection;
            }
        }
コード例 #12
0
    private void OnCollisionStay2D(Collision2D collision)
    {
        int angle = (int)Mathf.Abs(Vector2.Angle(collision.GetContact(0).normal, Vector2.right));

        if (angle <= 180 && angle >= 130)
        {
            movRightBlock = true;
        }
        else
        {
            movRightBlock = false;
        }
        if (angle >= 0 && angle <= 40)
        {
            movLeftBlock = true;
        }
        else
        {
            movLeftBlock = false;
        }
        //Debug.Log(angle);
    }
コード例 #13
0
ファイル: PongBall.cs プロジェクト: rubyleehs/Love-Pong
    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (timeSinceLastCollision > 0)
        {
            timeSinceLastCollision = 0;
        }

        if (collision.transform.CompareTag("Paddle"))
        {
            moveDir = (transform.position - collision.transform.position).normalized;
            collision.transform.parent.parent.GetComponent <PongPaddle>().Set(qString, initialColor);
            speed *= 1.085f;
        }
        else
        {
            float avgSpeed = (collision.transform.GetComponent <PongBall>().speed + speed) * 0.5f;
            speed   = avgSpeed;
            moveDir = Vector2.Reflect(moveDir, collision.GetContact(0).normal);
        }

        moveDir = moveDir.normalized;
    }
コード例 #14
0
 private void OnCollisionEnter2D(Collision2D collision)
 {
     if (collision.gameObject.tag == "Projectile")
     {
         return;
     }
     if (collision.gameObject.tag == "Player")
     {
         return;
     }
     //if (collision.gameObject.GetComponent<Projectile>() != null) return;
     //if (collision.gameObject.GetComponent<PlayerMovement>() != null) return;
     if (collision.gameObject.layer == 11) // wall layer
     {
         ContactPoint2D contact = collision.GetContact(0);
         if (contact.normal.x != 0f)
         {
             dir.x    = -dir.x;
             sr.flipX = !sr.flipX;
         }
     }
 }
コード例 #15
0
    /* Hay que hace que deje de detectar que está en la pared de alguna manera AQUI O EN UN UPDATE, VEREMOS
     * private void OnCollisionExit2D(Collision2D collision)
     * {
     *  onWall = 0;
     *  animator.SetBool("OnWall", false);
     * }*/

    void OnCollisionEnter2D(Collision2D collision)
    {
        ContactPoint2D[] contacts = new ContactPoint2D[collision.contactCount];
        collision.GetContacts(contacts);
        bool pointDown = false;

        foreach (ContactPoint2D contact in contacts)
        {
            //GameObject cube = Instantiate(debugCube);
            //cube.transform.position = contact.point;
            if (Vector2.Dot(contact.normal, Vector3.up) > 0.3)
            {
                pointDown = true;
                break;
            }
        }

        if (collision.gameObject.layer == 8 /*ground*/ && pointDown && !isGrounded)
        {
            contactedGround(collision.GetContact(0).point);
        }
    }
コード例 #16
0
ファイル: Ball.cs プロジェクト: Miki96/adaptive-ponger
    private void OnCollisionEnter2D(Collision2D collision)
    {
        string tag = collision.gameObject.tag;

        // check if goal
        if (tag == "BlueWall")
        {
            gm.Score(0);
        }
        else if (tag == "RedWall")
        {
            gm.Score(1);
        }

        // check if player
        if (tag == "RedPlayer" || tag == "BluePlayer")
        {
            speed += speedChange;

            float pos   = collision.transform.position.x;
            float width = collision.transform.localScale.x;
            float hit   = collision.GetContact(0).point.x;

            float v     = (hit - pos) / (width / 2);
            float angle = (Mathf.PI / 2) - v * (Mathf.PI / 180) * maxAngle;

            Vector2 bounce = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));

            if (tag == "BluePlayer")
            {
                bounce.y *= -1;
            }

            rb.velocity = bounce * speed;

            // adapt color
            ChangeColor(collision.gameObject.GetComponent <SpriteRenderer>().color);
        }
    }
コード例 #17
0
    //If it hits an enemy, turn around
    //If it hits a player and the player hits it from the top, kill the enemy. Otherwise kill the player
    public void OnCollisionEnter2D(Collision2D col)
    {
        if (col.transform.tag == "Enemy")
        {
            Velocity *= -1;
        }

        if (col.transform.tag == "Player")
        {
            if (col.GetContact(0).normal.y <= -0.5f)
            {
                GetComponentInParent <AchievementEnemies>().UpdateEnemies(this);
                col.rigidbody.velocity *= -2;
                Destroy(gameObject);
            }
            else
            {
                Velocity *= 1;
                KillPlayer();
            }
        }
    }
コード例 #18
0
    // Handles collisions with platforms
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "platform" && moveState != MoveStates.IDLE && CheckBelowGhost())
        {
            //// Collect contact info
            //ContactPoint2D contactPoint = collision.GetContact(0);
            //if (contactPoint.normal.y < 1f) return;

            // Velocity magnitude large enough to cause sound to trigger
            if (collision.relativeVelocity.magnitude > 4)
            {
                GameObject impact = (collision.collider.name == "greenPlatform") ? impact = Instantiate(greenImpact, null) : impact = Instantiate(redImpact, null);
                Screenshake.smallShakeEvent.Invoke();
                ContactPoint2D contact = collision.GetContact(0);
                impact.transform.position = contact.point;
                landSound.pitch           = Random.Range(.5f, .8f);
                landSound.Play();
            }
            moveState  = MoveStates.IDLE;
            isGrounded = true;
        }
    }
コード例 #19
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag.Equals("Ball"))
        {
            Rigidbody2D rb = collision.collider.GetComponent <Rigidbody2D>();

            //Get Collision point on paddle
            var   contactPoint = collision.GetContact(0);
            float cpY          = contactPoint.point.y;
            float y            = transform.position.y;

            //sets the y cord at the top of the paddle
            y += transform.localScale.y / 2;

            //Normalized impact point
            float nImapact = (y - cpY) / transform.localScale.y;

            //Redirects the ball in dependence of the impact point
            if (nImapact < 0.2f)
            {
                contactPoint.rigidbody.AddForce(Vector2.up * 80f);
            }
            else if (nImapact < 0.4f)
            {
                contactPoint.rigidbody.AddForce(Vector2.up * 60f);
            }
            else if (nImapact < 0.6f)
            {
            }
            else if (nImapact < 0.8f)
            {
                contactPoint.rigidbody.AddForce(Vector2.up * -60f);
            }
            else if (nImapact < 1)
            {
                contactPoint.rigidbody.AddForce(Vector2.up * -80f);
            }
        }
    }
コード例 #20
0
ファイル: HeroMove.cs プロジェクト: GrapeWang/U3D_learn
    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.collider.tag == "Enemy_circle" || col.collider.tag == "Enemy_square" || col.collider.tag == "Enemy_triangle")
        {
            DataManager.heroHp = DataManager.heroHp - EnemyColDamage;
            lifebar.value      = DataManager.heroHp;
            AudioManager.instance.playEnemyFX(ColClip);
            coleffect = GameObject.Instantiate(ColEffect, col.GetContact(0).point, Quaternion.identity);
            Destroy(coleffect, 1f);
            if (DataManager.heroHp <= 0)
            {
                Die();
            }
        }

        if (col.collider.tag == "Bonus_circle")
        {
            Bulnum[0]       += BonusBulnum;
            Bulnum[0]        = Mathf.Clamp(Bulnum[0], 0, BulnumMax);
            BnumBar[0].value = Bulnum[0];
            BnumText[0].text = Bulnum[0].ToString();
        }

        if (col.collider.tag == "Bonus_square")
        {
            Bulnum[1]       += BonusBulnum;
            Bulnum[1]        = Mathf.Clamp(Bulnum[1], 0, BulnumMax);
            BnumBar[1].value = Bulnum[1];
            BnumText[1].text = Bulnum[1].ToString();
        }

        if (col.collider.tag == "Bonus_triangle")
        {
            Bulnum[2]       += BonusBulnum;
            Bulnum[2]        = Mathf.Clamp(Bulnum[2], 0, BulnumMax);
            BnumBar[2].value = Bulnum[2];
            BnumText[2].text = Bulnum[2].ToString();
        }
    }
コード例 #21
0
    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.layer == 8)
        {
            // car collision with mine
            Destroy(other.gameObject);  // destroy the mine

            // play explosion
            GameObject explosion = GameObject.Instantiate(Resources.Load("Effects/Explosion") as GameObject);
            explosion.transform.position = other.gameObject.transform.position;
            explosion.transform.Rotate(0, 0, Random.Range(0, 360));     // randomize z-rotation
            explosion.transform.localScale *= Random.Range(0.8f, 1.2f); // randomize scale

            // push the car back
            int     force           = 18000;
            Vector2 pushDir         = new Vector2();
            Vector2 collisionNormal = other.GetContact(0).normal;
            pushDir.x = collisionNormal.x;
            pushDir.y = collisionNormal.y;
            Rigidbody2D.AddForce(pushDir * force, ForceMode2D.Impulse);
        }
    }
コード例 #22
0
    private void OnCollisionEnter2D(Collision2D other)
    {
        ContactPoint2D contact = other.GetContact(0);

        //  Debug.Log(contact.otherCollider.name + "hit " + contact.collider.name);
        if (contact.collider.tag == "Spike")
        {
            isKnock = true;
            AudioManager.instance.PlaySound("Princess_Hurt3");
            anim.SetBool("isKnock", isKnock); health -= 1f;
        }

        if (contact.collider.tag == "Enemy")

        {
            //Physics2D.IgnoreCollision(GetComponent<Collider2D>(), contact.collider.gameObject.GetComponent<BoxCollider2D>(), true); Debug.Log("IgnoredBox");

            isKnock = true;

            anim.SetBool("isKnock", isKnock);
        }
    }
コード例 #23
0
    private void OnCollisionEnter2D(Collision2D other)
    {
        ContactPoint2D contact = other.GetContact(0);

        if (other.transform.tag == "Player")
        {
            if (!isFalling)
            {
                if (player.isTackling)
                {
                    rb.AddForce(new Vector2(Random.Range(50, 65), 40), ForceMode2D.Impulse);
                    PlayerHelper.instance.AddSmashingEnemyScore();
                    SoundManager.Instance.PlaySoundEffect(punchEffect);
                    Fall();
                }
                else
                {
                    player.playerscript.Die();
                }
            }
        }

        if (other.transform.tag == "Ground")
        {
            if (isFalling)
            {
                Vector2 direction = contact.point - new Vector2(transform.position.x, transform.position.y);
                if (direction.x > 0)
                {
                    anim.SetTrigger("Wall");
                    rb.AddForce(new Vector2(-10, 5), ForceMode2D.Impulse);
                }
                else if (direction.y < 0)
                {
                    anim.SetTrigger("Ground");
                }
            }
        }
    }
コード例 #24
0
        private void OnCollisionEnter2D(Collision2D other)
        {
            if (!other.gameObject.CompareTag("Ball"))
            {
                return;
            }
            if (collisionName != "")
            {
                return;
            }
            collisionName = other.otherCollider.name;

            // Know which body of tower got hit
            var contact = other.GetContact(0);

            var damage = CalculateDamage(contact, other);

            Hit(damage);
            _damageIndicator.Spawn(Mathf.RoundToInt(damage), contact.point, contact.normal.normalized * -1, IsWeakPoint(contact));
            ProcessEffect(contact);
            ProcessAudio(contact);
        }
コード例 #25
0
 void OnCollisionEnter2D(Collision2D collision)
 {
     if (collision.collider.gameObject.layer == 9)
     {
         ContactPoint2D cp;
         for (int i = 0; i < collision.contactCount; i++)
         {
             cp = collision.GetContact(i);
             rgdb.AddForce(collision.contacts[0].normal * collision.relativeVelocity.magnitude * 200);
             if (cp.otherCollider.gameObject.layer != 0)
             {
                 Debug.Log("HP = " + hitPlayer((int)(collision.relativeVelocity.magnitude * 25)));
                 break;
             }
             else
             {
                 Debug.Log("Menor Hit = " + hitPlayer((int)(collision.relativeVelocity.magnitude * 10)));
                 break;
             }
         }
     }
 }
コード例 #26
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            Vector2 contact_point = collision.GetContact(0).normal;
            player_logic.player_speed = 0;
            if (contact_point == new Vector2(0.0f, -1.0f))
            {
                StartCoroutine(player_logic.KnockUp(0.2f, 300, Vector2.up));
                FindObjectOfType <AudioManager>().Play("ShroomJump");
            }
            else if (contact_point == new Vector2(1.0f, 0.0f))
            {
                StartCoroutine(player_logic.SlowDown(1.8f));
                StartCoroutine(player_logic.KnockBack(0.2f, 750, Vector2.left));
                // StartCoroutine(player_logic.KnockUp(0.2f, 150, Vector2.up));

                FindObjectOfType <AudioManager>().Play("LoseSound");
                FindObjectOfType <AudioManager>().Play("ShroomKnockBack");
            }
        }
    }
コード例 #27
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (level == BlockType.Unbreakable)
        {
            return;
        }
        hits++;
        TriggerParticles(collision.GetContact(0).point);
        var points = Random.Range(pointsPerHit, pointsPerHit + 20);

        manager.increaseScore(points);
        if (hits >= maxHits)
        {
            manager.DecreaseBlockAmount();
            Destroy(gameObject);
        }
        if (hits >= BlockSprites.Length)
        {
            return;
        }
        GetComponent <SpriteRenderer>().sprite = BlockSprites[hits];
    }
コード例 #28
0
    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Pad")
        {
            float          padhalfwidth = other.collider.bounds.extents.x;
            ContactPoint2D contact      = other.GetContact(0); //Just get the first contact point
            float          outAngle     = (contact.point.x - other.transform.position.x) / padhalfwidth * 45f;

            //Abort if it is an edge hit
            if (outAngle > 45f || outAngle < -45f)
            {
                return;
            }

            //Convert angle for use with unit circle
            outAngle = 90f - (outAngle);
            float   speed       = thisRigidbody.velocity.magnitude;
            Vector2 newVelocity = speed * ExtentionMethods.DegreeToVector2(outAngle);

            thisRigidbody.velocity = newVelocity;
        }
    }
コード例 #29
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Physics2D.IgnoreCollision(GetComponent <Collider2D>(), collision.collider);

        ContactPoint2D contact = collision.GetContact(0);

        if (contact.collider.gameObject.CompareTag(ReflectorTag))
        {
            m_shotDirection = Vector2.Reflect(m_shotDirection, contact.normal);

            m_shotDirection.Normalize();
        }
        else
        {
            // reflect.Play();
            reflect_particle particle = Instantiate(reflect.GetComponent <reflect_particle>());
            particle.transform.parent     = collision.gameObject.transform;
            particle.transform.localScale = Vector3.one;
            particle.transform.position   = collision.contacts[0].point + collision.contacts[0].normal * 0.01f;
            float cosTheta = Vector3.Dot(collision.contacts[0].normal, Vector3.up);
            float theta    = Mathf.Acos(cosTheta);
            Debug.Log(theta);
            particle.transform.rotation = Quaternion.Euler(-90 - theta * 180 / Mathf.PI, 90, -90);

            particle.Play();
            //reflect.GetComponent<reflect_particle>().play();
            //Debug.Log("shoot" + "   :  " + reflect.isPlaying);


            InanimateObject obj = contact.collider.gameObject.GetComponent <InanimateObject>();
            if (obj)
            {
                obj.ApplyGravity(m_gravityDirection);
            }
            killTime        = m_timeAlive;
            m_shotDirection = Vector3.zero;
            GetComponent <Collider2D>().enabled = false;
        }
    }
コード例 #30
0
ファイル: Snapper.cs プロジェクト: rplnt/ludumdare45
    private void OnCollisionEnter2D(Collision2D collision)
    {
        //Debug.Log("Snapper:OnCollisionEnter2D");
        if (collision.gameObject.CompareTag("Unit") && collision.gameObject.GetComponent <Snapper>() == null)
        {
            bool respawn = SnapOnApplyDirectlyToTheForehead(collision.gameObject);
            if (respawn)
            {
                ls.SpawnRandom();
            }
        }

        if (collision.gameObject.CompareTag("Enemy"))
        {
            ContactPoint2D contact = collision.GetContact(0);
            if (contact.otherCollider.gameObject == gameObject)
            {
                Debug.Log("Killing " + gameObject.name);
                Die();
            }
        }
    }