How to spawn power-ups in random places inside a clamped screen?

Hi, I’m making this asteroids like game in the Android platform and what I want to do is spawn random power-ups without the power-ups going out the screen. I clamped the X and Y to the edges of the screen to prevent objects from going out of bounds.

So how do I spawn random power-ups without going out of the screen?

Here’s the clamped values:

var xPos : float = Mathf.Clamp(transform.position.x, Screen.width * .057, -Screen.width * .057);
var yPos : float = Mathf.Clamp(transform.position.y, Screen.height * .057, -Screen.height * .057);

And how do you spawn power-ups one at a time at a random time in a game? For example, only 1 power-up can spawn at a time then after getting that power-up, a timer with a random time ( let’s say 5 - 15 seconds after getting that power-up ) will count then another power-up will spawn.

I hope you get what I mean.

May you please provide me a sample javascript of this?

I appreciate the help of whoever’s going to help me here. Thank you :smiley:

It sounds like, in addition to having power-up(s) in the scene, you’ll want something like a power-up “manager” present to keep track of the power-ups in play. It doesn’t matter where this manager is in the scene, as long as it’s attached to something that’s always active (you could throw it on an empty GameObject if you want).

The manager should have a float timer. In its Update, run the timer down and then Instantiate a power-up where you want one. (You already have a means for clamping the position, so just do a couple random gens, make a Vector3 out of them, and feed that into Instantiate.)

Now, here’s a little trick–your power-up script should have, in addition to anything else you need (a health bonus, score, etc.), a field of the power-up manager type. When the manager Instantiates the power-up, it should do a line like the following:

powerup.powerupManager = this;

That will give the power-up a reference to the manager. But, ugh; why do you need to do this?! Well, when the power-up gets destroyed in the scene, this is a good way to tell the manager, “hey, there are no more power-ups around, so you should spawn one when you get a chance.” And you can do that by adding an OnDestroy callback to your power-up script:

void OnDestroy()
{
    powerupManager.timer = 5.0f;
}

Something like the above would tell the power-up manager to spawn another power-up in 5 seconds.

Note that I haven’t tried any of this :slight_smile: I just think it’d be a cool way to do it. Are there countless other ways to do it? Sure. Hope this sparked some ideas though.