Random object placement on walkables/region

Started by The creature, Thu 29/04/2021 18:53:41

Previous topic - Next topic

The creature

Hi everyone. I have a quetion and it might be a complicated one.

In one of my rooms I have 20 objects that are randomly being placed between 2 specified points:
Code: ags

  int Shallows_X = 960;
  int Shallows_Y = 960;
  object[1].SetPosition(Random(Shallows_X)+20, Random(Shallows_Y)+50);
  object[2].SetPosition(Random(Shallows_X)+20, Random(Shallows_Y)+50);
  etc.....


This is fine but there are areas within my environment (like walls and other solid objects I'd ideally not want these objects to be placed on. Is there a way to code in a check that places each object randomly on a walkable area. I am using regions for another game system and use multiple regions but I am only using one walkable area per room (at the moment at least).

Any help is appreciated as it would make such a big visual difference.

Khris

You can use  GetWalkableAreaAtRoom(int x, int y)  to check the coordinates. Use a while loop to keep generating new ones until the area is #1.

Matti

You can also significantly shorten your code if you use a loop to iterate through the objects.

Untestet:
Code: ags

  int Shallows_X = 960;
  int Shallows_Y = 960;
  
  for (int i = 1; i < 20; i ++)
  {
    int random_x = Random(Shallows_X)+20;
    int random_y = Random(Shallows_Y)+50;
    while (GetWalkableAreaAtRoom(random_x, random_y) != 1)
    {
      random_x = Random(Shallows_X)+20;
      random_y = Random(Shallows_Y)+50;
    }
    object[i].SetPosition(random_x, random_y);
  }
}

The creature

That's pretty amazing. I'm still getting to grips with while loops but it works a charm and really cuts things down a good bit!

Matti

I'm glad it worked out for you.

Unless you change those shallows-variables during the game you don't even need to use them. In that code you could just write Random(960) + 20;

SMF spam blocked by CleanTalk