Randomize object in a map

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Frasse

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: Areacode hosted at ImgBB — ImgBB
Snapshot: stor hosted at ImgBB — ImgBB

Thank you!

:bust_in_silhouette: Reply From: nwgdusr999

You forgot to ask your question! If it was how to move your nodes, you can simply set their position to random x,y coordinates. Normally you don’t want to set your Node’s position manually as it bypasses the physics engine, but in your case, seems to be exactly what you want.

You can detect the collision via the _physics_process(delta) method of your player or object collider. Your teleporter collider might make more sense as it might be able to also transport bullets, npcs, etc.

How to set their position to random x and y coordinates?

Frasse | 2019-12-01 16:40

:bust_in_silhouette: Reply From: Zylann

Like this?

# Randomize a position within the world rectangle
player.position = Vector2(rand_range(0, map_width), rand_range(0, map_height))

That’s assuming your map starts at (0,0) and extends towards right and bottom. Also note that in this example, if you use tiles, map_width and map_height would be in pixels, so if your tile size is 32x32, map_width would be 1344 * 32.