- Home /
Spawn objects at bottom of screen / camera
In endless vertical scroller games, If the camera moves vertically down, there are some objects that leave the camera view from the top. Is it possible to replace these objects at the bottom edge of the camera? This is what I tried, by subtracting the position vectors. Which didn't do the job the way I described above.
void Start()
{
Cam = Camera.main.transform;
}
void Update () {
var Pos = Cam.position-transform.position;
Debug.Log(Pos.y);
if(Pos.y<0){
transform.position = new Vector3(transform.position.x, Cam.position.y+1, 0f);
}
}
Any code example for solution would be really helpful.
Answer by dmitriy-untilov · Feb 21, 2018 at 01:33 PM
You need to use Camera.ScreenToWorldPoint
function which convert position from Screen to World space, so in that way you can spawn objects at the bottom edge of the camera. See this article from unitydocs: https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
for example:
var screenBottomCenter = new Vector3(Screen.width/2, Screen.height, 0);
var inWorld = Camera.main.ScreenToWorldPoint(screenBottomCenter);
Answer by mauriciomb · Jun 16, 2020 at 10:45 PM
This might be a bit late but the code you provided put my start position to the top center of the screen. I changed it to this to get the bottom center:
var screenBottomCenter = new Vector3(Screen.width/2, 0, 0); var inWorld = Camera.main.ScreenToWorldPoint(screenBottomCenter);
Your answer
Follow this Question
Related Questions
Move camera when mouse is near the edges of the screen 1 Answer
Child GameObject is aligned to world axis and not the parents axis (UPDATE) 1 Answer
Trouble converting transform.position to C# 1 Answer
How to find total distance from start to end of an array which stores positions in vector3? 2 Answers
Object not centering with screen.width/2 0 Answers