2d box collider as trigger from four direction

    //Variable to hold the contacts
    ContactPoint2D[] contacts = new ContactPoint2D[2];

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            //Get all contact points and save to the contacts array variable
            other.GetContacts(contacts);

            Vector3 normal = contacts[0].normal;
            Vector2 point = contacts[0].point;

            Debug.Log(point);
            cam.transform.position = camChangePosition;

        }
    }

how is it possible to detect that from which side of a 2d box collider player is triggered to that?

Check the dot product of your contact normal with Vector3.right.

If the dot product is positive, then the player contacted the right side.
If the dot product is negative, the player contacted the left side.

1 Like

may you please give a code snippet?

what about up and down?

Same thing but with Vector3.up.

If you want to check all 4 directions, you could calculate the angle between each of the 4 cardinal directions (left up right down) and the contact normal. Then just pick the one that returns the smallest angle.

1 Like

this is exactly what i need, however i am a beginner programmer.

may you give some code?

I would do a bit of searching on this (dot products, determining collision edges) and you should find something.

Another (less elegant) solution: replace your box collider with an empty GameObject that has four Edge Colliders as children, in the right spatial configuration, and each of those checks for collision on itself.

1 Like

i prefer then to search about Dot product , however if there is some code please leave them here.

1 Like

is there any code snippet please ? i cant understand it yet

    [SerializeField]
    private Transform player;



    private void Update()
    {
        // a vector to show direction and distance from player to the gameobject
        Vector3 distance = player.position - transform.position;

        // distance vector which is a unit vector
        distance.Normalize();


        // a line from gameobject towards player
        Debug.DrawRay(transform.position, distance, Color.green);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
         


        }
    }

here i could understand to calculate the vector distance between the 2d box collider and the player.
then i made the distance vector as unit vector.

my question is how is possible to detect from which main direction right, left , up or down the player is triggered the 2d box collider?

i hope someone give me a comprehensive answer. thanks.