Tuesday, July 19, 2022
HomeGame Developmentphysics - Unity physics2d object repelling itself from static colliders

physics – Unity physics2d object repelling itself from static colliders


In the long run emitting raycasts in all instructions and including a drive in the wrong way of the closest hit labored fairly properly

    void Radar()
    {
        float vary = 2f;
        float drive = 15;
        
        float increment = 10f;
        Vector2 course = Vector2.up;
        Vector2 closestPoint = Vector2.zero;
        float minDistance = float.PositiveInfinity;
        bool discovered = false;
        
        for (int i = 0; i < 360/increment; i++)
        {
            RaycastHit2D hit =  Physics2D.Raycast(rework.place, course, vary);
            if (hit.collider != null)
            {
                discovered = true;
                float distance = Vector2.Distance(hit.level, rework.place);
                Debug.DrawLine(rework.place, closestPoint);
                if (distance < minDistance)
                    closestPoint = hit.level;
                minDistance = Mathf.Min(distance, minDistance);
            }
            course = Hutl.rotatePointDegrees(course, increment);
        }

        if (discovered)
        {
            Debug.DrawLine(rework.place, closestPoint);
            Vector2 forceDirection = ((Vector2) rework.place - closestPoint).normalized;
            rb.AddForce(forceDirection * drive);
        }
```

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments