- Home /
Set game object position relative to the Camera
Hello,
I'm coding a script that reads a text file with a tilemap(like the ones from the tiled tool), and then creates game objects in the game world, each representing a tile. The thing is, after creating the game objects, I try to position them relative to top left corner of the screen, like in a grid. But whenever I run the game, the objects are positioned far from the camera, and with a great space between then. Here is the code who creates and set the position of the objects:
void SetMap() {
for (int i = 0; i < tileMatrix.Count(); i++) {
if (tileMatrix[i] > -1) {
print(i);
map.Add(GameObject.Instantiate(tileObjects[tileMatrix[i]]) as GameObject);
map[i].transform.parent = gameObject.transform;
}
else {
map.Add(null);
}
}
for(int i = 0; i < mapHeight; i++) {
for(int j = 0; j < mapWidth; j++) {
print(j + i * mapWidth);
if(map[j + (i * mapWidth)] != null)
map[j + (i * mapWidth)].transform.localPosition = new Vector3(i * tileWidth, Screen.height - j * tileHeight);
}
}
}
This code is in a object who is the parent of all tiles. Also, I'm using a canvas with "Screen Space - Camera", the game is supposed to be 2D topdown with the camera locked in a position, and the tile objects are prefabs with only 32x32 sprites.
It is my intention to use this code to create objects starting from the top left corner, each adjacent to the other.
After some research, I believe it might have something to do with the difference between units in the game world and pixels. Still, don't have a clue on which I'm actually using in this code, which to use for my intended purpose, or if this is actually the problem.
Any help is very well appreciated!
EDIT: The screenshots from the game view, the main camera inspector, and from the tile object(greentestblock) who is spawning outside the view:
Answer by tormentoarmagedoom · Sep 19, 2017 at 08:12 PM
Hello @gerudoking !
I don't understand what happens whith the objects, "away from the camera"? Can you post some screenshots to see it?
If the camera is immobile, you should be able to instantiate at concrete world position. You are doing this:
Instantiate(tileObjects[tileMatrix[i]])
Why not instantiate giving the position?
Instantiate(tileObjects[tileMatrix[i]], position, rotation)
Hey @tormentoarmagedoom , I posted some screenshots in the question. Here's another one (from the canvas) as I can't post more than two images:
Also, is there a difference between during the instantiation provide the position and provide it after the instantiation? I'm assigning the position later because of the logic I thought for positioning the objects.