Hey guys, I’ve started learning Unity over the past month or so and am current working on an Asteroids game. I’m currently able to spawn different size asteroids with random rotation and velocity (that are bounded within a range). However, one thing I am struggling with is to get the asteroid to spawn in a random place, OFF camera, and move into camera.
I currently have a ScreenWrap script that will automatically wrap objects to the opposite side of the stage upon exiting one side. For example, if you fly your ship off the left side of the stage you will reappear coming from the right edge of the stage.
What I’m trying to do now, is spawn the asteroids off screen, apply the velocity, and then activate the ScreenWrap script upon entering the stage.
Here is what I have so far to place the asteroids (in my asteroids script):
function SetRandomPositions () {
// Start the asteroid in a random place inside the camera
// Get the edge positions of the camera
var limitMin:Vector3 = Camera.main.ScreenToWorldPoint(Vector3(0, 0, Camera.main.transform.position.y));
var limitMax:Vector3 = Camera.main.ScreenToWorldPoint(Vector3(Screen.width, Screen.height, Camera.main.transform.position.y));
// Place the asteroid on the stage in a random place
transform.position.x = Random.Range(limitMin.x, limitMax.x);
transform.position.z = Random.Range(limitMin.z, limitMax.z);
}
This script currently just places them on the screen in a random place. However, I need to place them OUTSIDE the stage when spawning. This way an asteroid doesn’t spawn on top of the player, as well as, not looking like it just appears out of nowhere.
There is a variable inside of the ScreenWrap script that has the object’s offset. This variable allows the object to move off the screen just enough so you don’t see it “jump” to the other side. Using this variable, I started to write an “outer spawn box”, but I can’t figure out how to constrain the asteroid to be inside the “spawn box” but outside the “stage box”.
var outerSpawnMin:Vector3 = Vector3(limitMin.x + (asteroidSizeOffset * 2), limitMin.z + (asteroidSizeOffset * 2));
var outerSpawnMax:Vector3 = Vector3(limitMax.x + (asteroidSizeOffset * 2), limitMax.z + (asteroidSizeOffset * 2));
Here is a link to play the current build to get an idea, and attached is an image that best describes what I’m trying to do. Any help would be greatly appreciated!
