Search Unity

Making a grid-based background

Discussion in '2D' started by ShellpadInteractive, Dec 14, 2014.

  1. ShellpadInteractive

    ShellpadInteractive

    Joined:
    Oct 20, 2014
    Posts:
    13
    Dear Unity users,

    I am currently working on my second Unity project. I am trying to make a tile-based background image, meaning that I want to place tiles next to each other in a grid to form a full background image. So I wrote a method which basically places my tiles in a grid
    Code (CSharp):
    1.  
    2. for (int y = 0; y < level.Height; ++y)
    3.       for (int x = 0; x < level.Width; ++x)
    4.             {
    5.                int xPos = x * this.tileWidth;
    6.                int yPos = y * this.tileHeight;
    7.                AddTile(xPos, yPos, "Background/Wall");
    8.              }
    9.  
    The tileWidth and Height in this case are equal to the tile image width and height in pixels.

    What I want it to do is to place the tiles nicely in a grid exactly next to each other. But something fishy is going on with the coordinates in the Unity system. When I run my code without any modifications this is what I get:

    a bit closer:


    So ok, pixel coordinates and actual world coordinates aren't the same. That is clear. At this point I started to look for methods that could transform the world coordinates to pixel coordinates and I stumbled upon Camera.ScreenToWorldPoint() which supposedly returned the coordinates I wanted. But when I applied that method this is what came out:

    Looks pretty good right? The tiles are nicely in a grid without any gaps inbetween. But wait...

    Apparantly, tiles still overlap and aren't perfectly placed next to each other in a grid.

    So now my question, how can I place my tiles nicely in a grid using pixel coordinates?
     
  2. ShellpadInteractive

    ShellpadInteractive

    Joined:
    Oct 20, 2014
    Posts:
    13
    Ok, so I found the solution to my problem. I had to use the SpriteRenderer.bounds.size.x command to get the size of the texture I used in the Unity world. Using that as my tileWidth and tileHeight placed the tiles exactly at the right positions.