So, im creating a game where I need to have objects spawn on the right side of the screen at random points of the Y-Axis then fly to the left to be collected by the player. How would I go about coding this in C#?
I haven’t checked it but this should get you close/started for the spawn point generation:
float spawnY = Random.Range(0, Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.Height)).y);
Vector2 spawnPosition = new Vector2(Camera.main.ScreenToWorldPoint(new Vector2(Screen.Width, 0)).x, spawnY);
The first line will randomly generate a position along the Y axis but within the bounds of the screen. The second line will generate the spawn position at the right edge of the screen using the variable from the first line. Add a buffer to Screen.Width if you want the object to be spawned off screen and not on screen.Good luck.
P.S. > Updated the code a bit, I realized I had an error in there, still haven’t checked it in game or anything though so you will have to do that.
I am doing something very similar to this, but completely random spawning wasn’t quite cutting it.
What I did was create an empty GameObject on the edge of screen the size of the area I wanted objects to spawn from.
I then created 6 smaller Empty objects and placed them in a row within my “spawnArea” object.
I then used a random.range int to determine which spawnPoint to choose.
My spawning script is attached to the parent spawnArea object, and has the 6 spawnPoint objects’ transforms within it.
BlueSin’s approach is fine as well. Using either the Camera height/width or manually inputted coordinates will do the trick.
I also recommend you run through the Space Shooter Project, as it is quite short and will give you the knowledge you need for questions such as this. In fact this exact question will be answered.
Thanks for the response, ill give the tutorial a go!
Thanks!
No problem, keep in mind I just updated the code though so you might want to refresh your screen. ^^
So, I followed this tutorial but theres one problem. My game has a moving camera and this tutorial only spawns the objects on one spot (as opposed to following the camera and spewing out the points as I go.) Have any idea how I could make this so it will follow my camera?
The code I gave you will do that.
So, would I attach that code to a empty game object? or how would I go about doing that?
Sorry, I’m sort of a noob to coding
Hi MCamac55, did you maange to resolve this please?