Search Unity

Instantiate object within a Transform

Discussion in 'Scripting' started by o12497639, Feb 16, 2019.

  1. o12497639

    o12497639

    Joined:
    Feb 16, 2019
    Posts:
    26
    I have a spawn area, and I would like to spawn objects within boundaries of it.

    First thought was to use random numbers between X and Y, limit it to size of spawn object and use that to spawn items inside given range, but the idea breaks down because the item is rotated, so with this method, the item might still land out of spawn area. It would be as if you had 2D square image and rotate it 45 degrees.

    I had visited couple solutions, but I cannot regoogle them. There was something about boundaries, but the link was dead and I couldn't find modern reference. Most solutions revolve around perfectly unrotated squares, so simple math wouldn't work.

    I could use algebra and Pythagorean Theorem to determine proper length and coordinates; and define custom boundaries, but I feel like that could tax system more than the game should handle (considering the context), I believe there might be a simpler way as well.
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    o12497639 likes this.
  3. o12497639

    o12497639

    Joined:
    Feb 16, 2019
    Posts:
    26
    It seems to require some magic or extensive programming to work, I think I'll just stick to math.
     
  4. mbaske

    mbaske

    Joined:
    Dec 31, 2017
    Posts:
    473
    Let's say you have a cube/cuboid that is rotated around its center and you want to spawn objects inside it. You could create non-rotated bounds at the cube's position, matching its size but without the rotation. Spawn objects inside these bounds and then rotate your objects around the center, applying the rotation of your original cube.
     
  5. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    If you dont like that solution you could also use transform.TransformPoint to get a point in local space(basically a transform with no position or rotation) into global space.