Pickup Challenge and 2D

While using the existing (3D) sphere collider will work in a 2D game (it did for me at least) - just for cleanliness sake and to help me understand what was going on… adding the below methods to PlayerController.cs will do the job in 2D land.

Just add a call to InteractWithComponent2D() in the Update method on PlayerController.cs.

    private bool InteractWithComponent2D()
    {
        RaycastHit2D[] hits = RaycastAllSorted2D();
        foreach (RaycastHit2D hit in hits)
        {
            IRaycastable[] raycastables = hit.transform.GetComponents<IRaycastable>();
            foreach (IRaycastable raycastable in raycastables)
            {
                if (raycastable.HandleRaycast(this))
                {
                    SetCursor(raycastable.GetCursorType());
                    return true;
                }
            }
        }
        return false;
    }

    RaycastHit2D[] RaycastAllSorted2D()
    {
        var hits = Physics2D.CircleCastAll(GetMouseRay2D(), raycastRadius, Vector2.zero);
        float[] distances = new float[hits.Length];
        for (int i = 0; i < hits.Length; i++)
        {
            distances[i] = hits[i].distance;
        }
        Array.Sort(distances, hits);
        return hits;
    }

    private static Vector2 GetMouseRay2D()
    {
        return Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

I created an ‘Armour’ pickup with a Circle Collider 2D (mind the pixels!):

1 Like

Well done!

Privacy & Terms