0
\$\begingroup\$

Is there a way to have a 2D object repel itself from any colliders within a radius? A PointEffector2D will repel other colliders, but no force is exerted on the object containing the effector.

I also tried to use OnCollisionEnter2D() and OnCollisionStay2D() on a kinematic rigidbody2D to detect other colliders and emit a force in that direction, but it only seems to register collisions with dynamic rigidbodies and not static colliders.

The use case is as a power up for spaceship to make it bounce off the terrain which is composed of EdgeColliders.

\$\endgroup\$
1
  • \$\begingroup\$ "it only seems to register collisions with dynamic rigidbodies and not static colliders." - does the object itself have a dynamic Rigidbody2D attached? Collision and trigger overlap events will not be sent for collisions between two static colliders, since they're meant to be "static" as in not moving. So at least one collider of the pair must have a body. \$\endgroup\$
    – DMGregory
    Jul 18 at 16:28

1 Answer 1

0
\$\begingroup\$

In the end emitting raycasts in all directions and adding a force in the opposite direction of the nearest hit worked quite well

    void Radar()
    {
        float range = 2f;
        float force = 15;
        
        float increment = 10f;
        Vector2 direction = Vector2.up;
        Vector2 closestPoint = Vector2.zero;
        float minDistance = float.PositiveInfinity;
        bool found = false;
        
        for (int i = 0; i < 360/increment; i++)
        {
            RaycastHit2D hit =  Physics2D.Raycast(transform.position, direction, range);
            if (hit.collider != null)
            {
                found = true;
                float distance = Vector2.Distance(hit.point, transform.position);
                Debug.DrawLine(transform.position, closestPoint);
                if (distance < minDistance)
                    closestPoint = hit.point;
                minDistance = Mathf.Min(distance, minDistance);
            }
            direction = Hutl.rotatePointDegrees(direction, increment);
        }

        if (found)
        {
            Debug.DrawLine(transform.position, closestPoint);
            Vector2 forceDirection = ((Vector2) transform.position - closestPoint).normalized;
            rb.AddForce(forceDirection * force);
        }
```
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .