- Home /
Instantiate gameobjects at random points on the screen
Dear fellow programmers
I'm very now to Unity and I was trying to make a boid simulation like Sebastian Lague did (His video). I started with a 2D screen and I want to instantiate 10 boids at random points on the screen.
Here is the code I tried. Located in void Start():
for (int i=0; i<11; i++) {
Instantiate(boid);
boid.transform.position = new Vector2(Random.Range(1, Screen.width), Random.Range(1, Screen.height));
}
I quickly realised that this is not going to work tho.
The (0, 0) point is at the center of the screen
I can't just take screen coordinates and convert them into world coordinates
I tried to put my vector2 in Camera.main.WorldToScreenPoint(). But it didn't work. It even put the object further away from the screen.
I did some extensive research over a few days. But I didn't find anything helpful.
I somehow excpected there is an easyer way to convert screen pixels to world coordinated. Like there is a multiplication factor or something.
Anyway I hope I was clear. If you have any more questions feel free to ask and thanks for your help in advance.
Answer by The-Peaceful · Apr 26, 2021 at 08:58 AM
You use Camera.main.WorldToScreenPoint()
, that would give you the opposite of what you want (world point to a point in pixel space), what you want is Camera.main.ScreenToWorldPoint()
:D The point (0,0) then is at the bottom left of the screen, as you can read in the documentation (link below)
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Ok so thats working. Thanks so much. But there is still a little bit of a weird problem. All the boids had a z value of -10. So the were not visible in the game view. I checked that the prefab value was set to 0 and it was. I applied a little bit of a crude fix and manually set all the boids z value to 0 in the code. But do you have any idea what could cause the boids to be instantiated at -10?
That's probably because the camera has a Z position of -10, so when you tell it to transform the 2D position into 3D world space, it just takes that value as the Z component of the vector. So setting it to 0 afterwards is just the right way to do it. :D
Ok thank you so much for your help :)
Your answer

Follow this Question
Related Questions
2D Touch Input Problem with ScreenToWorldPoint 1 Answer
ScreenToWorldPoint question 1 Answer
Camera.ScreenToWorldPoint with Perspective camera 1 Answer
Sprite Not Displaying In-game 0 Answers