This is the testing Godot forums! All forum posts unique to this forum will be deleted! Please use the main forums here for any posts you want to keep. All forum rules still apply.

How to randomize object position in a map

FrasseFrasse Posts: 4Member

Hello guys!
I have a 1344x768 map.
I have a sprite with collisionshape in Area2D. And i Have a player. I want that when the player enters the Area2D then it will disappear and then appear in a random place in my map. And then when the player enter it then it will disappear and appear in a new random place in the map.

Please check the images to understand me better:

Area2D code:

Thank you!


  • ben-gachowskiben-gachowski Posts: 6Member

    You can use the RandomNumberGenerator class to generate two float values, x, and y.
    Those values will be within a specified range, so for your map generate a x between 0 and 1344-1
    and a y between 0 and 768-1.
    Note that the upper bound is minus one, because you want to find a point inside the map.
    Then once you have the values, you need to check if the point is occupied, and if there is something already there, search the area around the point for a free space.

    Once you find the free spot, you can just move the Area2D to it. You don't have to free the Area2D and make a new one, moving it right to the new spot should have the same affect.

Leave a Comment

Rich Text Editor. To edit a paragraph's style, hit tab to get to the paragraph menu. From there you will be able to pick one style. Nothing defaults to paragraph. An inline formatting menu will show up when you select text. Hit tab to get into that menu. Some elements, such as rich link embeds, images, loading indicators, and error messages may get inserted into the editor. You may navigate to these using the arrow keys inside of the editor and delete them with the delete or backspace key.