Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Randomly placing objects near polygon collider 2D

Discussion in 'Scripting' started by epochplus5, Feb 18, 2021.

  1. epochplus5

    epochplus5

    Joined:
    Apr 19, 2020
    Posts:
    677
    I have a landscape that is covered with a polygon collider 2D. I want to randomly place missiles over the landscape but they cant touch the polygon collider or they will explode.

    any ideas how to accomplish this?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Use Physics2D.OverlapCircle to check if your missile radius is within a collider? It's a rather naive approach but possibly good enough depending on your situation.
     
  3. epochplus5

    epochplus5

    Joined:
    Apr 19, 2020
    Posts:
    677
    No, I have a 2D landscape that has different heights, and i want to spawn the missiles along the terrain, but they cant touch because if they do they will explode, though i could always enable their colliders just after launch.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,089
    Epoch! I always love your posts because you're always working on the next thing. Awesome.

    So for this I would pick a random spot from left to right at the top of your screen, then raycast down to "hit" the terrain and see how high it is at that point, and from that you can emplace your missile above the ground, or on a pedestal or whatever.

    Remember there are various flavors of Raycast in Physics2D:

    https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
    "Tell me if I hit any 2D colliders in the scene..." (filterable by LayerMask)

    https://docs.unity3d.com/ScriptReference/Collider2D.Raycast.html
    "Tell me if I hit this one specific Collider2D I have here." (this might be useful for a single ground collider, or small collection of ground colliders)