简体   繁体   中英

Contact point between OverlapCircle and certain collider in Unity

I am trying to get the contact point between a Collider and OverlapCircleAll to play an animation on that point.

This is the method I am using for the attack.

private IEnumerator BasicAttackBehaviour()
    {
        canAttack = false;
        Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPos, attackRange, whatIsEnemy);
        for (int i = 0; i < enemiesToDamage.Length; i++)
        {
            enemiesToDamage[i].GetComponentInParent<Enemy>().TakeDamage(damage);
        }
        PlayAttackAnimation();
        yield return new WaitForSeconds(attackDelay);
        canAttack = true;
    }

And this is the "TakenDamage" method:

public void TakeDamage(int damage)
    {
        health -= damage;
        GameObject bloodEffect = Instantiate(takenDamageVFX, transform.position, transform.rotation);
    }

I want to instantiate the VFX "bloodEffect" on the position the enemy is hitten instead of "transform.position".

看起来像这样

You may want to switch to CircleCastAll, it will give you contact points in world space coordinates:

https://docs.unity3d.com/ScriptReference/Physics2D.CircleCastAll.html

You can set the distance parameter to 0.0f if you don't want to do a moving circle and just a single non-moving circle.

Answering to my question and thanking to the boss whom resolved my question above, here goes my fix just in case someone needs to visualise the example.

private IEnumerator BasicAttackBehaviour2()
    {
        canAttack = false;
        RaycastHit2D[] raycastHits = Physics2D.CircleCastAll(attackPos, attackRange, directionLookingAt, 0, whatIsEnemies);
        for(int i = 0; i < raycastHits.Length; i++)
        {
            Vector2 pointHitten = raycastHits[i].point;
            raycastHits[i].collider.gameObject.GetComponent<Enemy>().TakeDamage(damage, pointHitten);
        }

        PlayAttackAnimation();
        yield return new WaitForSeconds(attackDelay);
        canAttack = true;
    }

Using CircleCastAll I am able to retrieve the point of the RaycastHit2D and pass it to the enemy.

And then, I can display the blood effect on the right position of the impact.

public void TakeDamage(int damage, Vector2 pointHitten)
    {
        health -= damage;
        GameObject bloodEffect = Instantiate(takenDamageVFX, pointHitten, transform.rotation);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM