- Home /
How to instantiate tiles based on a 2D Array into a Platform Game?
I'm building a very simple platform game using 2D array to build the map based on it.
There are two simple goals I want and I'm currently not finding the answer:
Ensure that the camera is 16:9 and my scene will be 100% displayed in it
Build a 2D platform tileset as in an array
My environment:
Unity 5.5.0f3 (in 2D Mode)
Camera projection ortographic size 10.9
Game displayed in 16:9
Tileset dimensions are 128x128 px
Here is my current code:
public Camera camera;
public GameObject prefab;
void Start () {
Vector3 pos = camera.ScreenToWorldPoint(new Vector3 (0, 0, 0));
Vector3 nextPosition = pos;
for (int i = 0; i < 32; i++)
{
for(int j=0; j < 18; j++)
{
GameObject a = Instantiate(prefab, new Vector3(nextPosition.x, nextPosition.y, 0), Quaternion.identity);
nextPosition = new Vector3(pos.x+(prefab.GetComponent<Renderer>().bounds.size.x)*i, pos.y+(prefab.GetComponent<Renderer>().bounds.size.y)*j,0);
}
}
}
There are 3 things to notice about it:
I'm using ScreenToWorldPoint to get me the position for 0,0,0
My building order goes from bottom left to top right, each iteration is put as the past position + block width/height (x and y)
I'm using a 16:9 for scheme which is 32:18
Using it, this is my result:
As you can see it stays out of the camera boundary and even tho both camera and code are 16:9, it exceeds 1 column. Also note that the instantiate point is exactly in the middle of my GameObject, so I start instantiating it as half of the gameObject's width and height, meaning:
Vector3 pos = camera.ScreenToWorldPoint(new Vector3 (64, 64, 0));
And the reuslt is the following:
Not what I expected at all, by trial and error I figured out it is suposed to be at 16,16:
Vector3 pos = camera.ScreenToWorldPoint(new Vector3 (16, 16, 0));
Now its a perfect fit, but it exceeds 1 line at the top and 1,5 columns at the right. Which shouldn't because they are both 16:9
I'm clearly doing something wrong but I can't see what, I've been through this problem in the past but I don't remember what I figured out.
Answer by mghffel · Jan 01, 2017 at 05:30 PM
I had trouble with my camera position a few days ago, but I fixed it by clicking the Main Camera in the scene's hierarchy and then adjusting the size variable until the camera fit perfectly around my scene.
$$anonymous$$y problem is not the camera size, I've tried to ajust this already, the real problem has to do with the code for positioning and filling the camera correctly.
Your answer
Follow this Question
Related Questions
My 2D tiles have holes in them 0 Answers
Player Gets Stuck On TilemapCollider2D 0 Answers
Load time of 2D TileMaps 0 Answers
how to keep static variables or 2d array value 0 Answers
How to store remaining durability of tiles? Tilemap 0 Answers