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: https://ibb.co/9b8xjn0
Snapshot: https://ibb.co/6JNs3tW

Thank you!

Answers

  • ben-gachowskiben-gachowski Posts: 5Member

    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

BoldItalicStrikethroughOrdered listUnordered list
Emoji
Image
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file