A way to make an Area2D apears and disapears randomly on the screen?

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

Thxs to tell if you know.

:bust_in_silhouette: Reply From: jgodfrey

That’s a pretty open-ended question. I can provide you with a few pointers (note, any code shown below was typed directly into this answer and is therefore untested - though it should be reasonably close):

Every Area2D has a visible boolean property - which can be seen in the inspector. Setting it to true makes the Area2D (and its children) visible… Setting it to false makes the Area2D (and its children) invisible. So, that’s your basic mechanism for controlling visibility of the item.

You can control that property in code by getting a reference to the Area2D and simply setting the value of the visible property. So, something like this:

$Area2D.visible = false

Beyond that, you’ll need to decide what mechanism to use to control the visibility.

One obvious and simple way would be to use a Timer. To do that, you’d add a timer to your scene and wire the timeout event to fire some code. In the code that fires, you could toggle the Area2D’s visibility as noted above and then reset the timer’s wait_time property to some random value again. That’ll cause the timer to count down again and eventually fire the same timeout code.

Also of note, you can easily toggle the state of boolean value (like the visible property) like this:

$Area2D.visible = !Area2D.visible

So, if you use something like that in your timeout code, it’ll switch between visible and invisible each time the timeout code fires. So, something like this:

func _on_Timer_timeout():
   var rng = RandomNumberGenerator.new()
   nextToggleSeconds = rng.randi_range(5, 15) # toggle in 5 to 15 seconds
   $Area2D.visible = !$Area2D.visible # switch visibility

There are certainly other ways to control the timing of the visibility toggle. For instance you could do it via monitoring some time_delta variable in _process(delta).

Hopefully, that gets you started…

Man, you’re really helpin me out, i’m so grateful. :slight_smile: But i got an error with the script:

‘identifier ‘nexttoggleseconds’ is not declared in the current scope.’

Syl | 2020-01-23 18:36

You probably need to brush up on your scripting skills…

However, that’s on oversight on my part… It’s missing a var reference:

var nextToggleSeconds = ...

jgodfrey | 2020-01-23 18:58

Cheers! That works great, but how to make it appear on random locations in the screen?

Syl | 2020-01-23 19:54

To assist others who come here looking for a specific answer in the future, I’d recommend that you open a new question - and limit it to a narrow, well-targeted topic.

jgodfrey | 2020-01-23 19:59

Okokok. I’ll do that.

Syl | 2020-01-23 20:54