Sign in to follow this  

Unity Drawing tiles on a grid

This topic is 3405 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

To make my 2D map (see this post) i have decided to split it up into smaller (256x256) OpenGL textures. Now i need some code to draw the tiles that are in view on the screen. I don't know whether to loop through all tiles and check if each will be visible on screen, or if i should use some fancy maths to calculate the array index of the start and end tiles in the x and y direction. Here is some of the code i have so far:
/*  numTileX and numTileY are the number of tiles in the x and y direction
 *  texTileSize is the size of the square texture (256x256)
 *  drawGLTexture function is listed below. Ignore imgW, imgH, wrapX, wrapY, and angle as these
 *        are not used here, i don't need to stretch or tile each tile
 */
void Map::draw() {
    // Also need to tile or stretch the background image.
    drawImage(background.image, 0, 0, screenWidth, screenHeight);

    for (int j = 0; j < numTileY; j++) {
        for (int i = 0; i < numTileX; i++) {
            drawGLTexture(tiles[j*numTileY+i].texId, i*texTileSize, j*texTileSize,
                     texTileSize, texTileSize, ...);
        }
    }
}

// In file Graphics.cpp
void graphics::drawGLTexture(GLuint id, int x, int y, int w, int h,
                int imgW, int imgH, int wrapX, int wrapY, float angle) {
    // Rotate the matrix if the image is at an angle
    if (angle != 0) {
        glPushMatrix();
        glRotatef(angle, 1.0f, 0.0f, 0.0f);
    }

    // Scale image coords to texture coords [0.0-1.0]
    float tw = 1.0f, th = 1.0f;
    if (wrapX == TILE)  tw = float(w)/float(imgW);
    if (wrapY == TILE)  th = float(h)/float(imgH);

    // Draw quad with texture
    glBindTexture(GL_TEXTURE_2D, id);
    glBegin(GL_QUADS);
    glTexCoord2f( 0,  0); glVertex2i( x,   y );
    glTexCoord2f( 0, th); glVertex2i( x,  y+h);
    glTexCoord2f(tw, th); glVertex2i(x+w, y+h);
    glTexCoord2f(tw,  0); glVertex2i(x+w,  y );
    glEnd();

    // Restore rotation
    if (angle != 0)
        glPopMatrix();
}


Here is a diagram of what i want: I need to draw the tiles that will be totally or partially visible on the screen. I also don't know if i should manually clip the tiles to the screen by drawing a quad with part of the texture on it, or if it would be faster if i just draw it partially off-screen and let OpenGL do the clipping. If anyone has similar code from their game or knows of a good website that explains how to do it then that would be great. Otherwise i would just like to know the best/easiest way to do it. thanks

Share this post


Link to post
Share on other sites
If all you need to render is less than 10 256x256 textures, then you can just render all totally or partly visible tiles, since this is peanuts for even an older graphics card. You will be amazed of just how many commands and textures you can throw after modern cards without notice.
For the detection of which tiles are visible, this will probably not be a bottleneck even with larger maps, but there are anyways at least 2 faster solutions.
One of them is to calculate the array index via the fancy math, as you described, but it really is not that tricky. Assuming your map starts at (0, 0), your world units are pixels, and you have saved the screen position (sp) as the lower left coordinate of the screen space (assuming GL coordinate system), you need to render tiles from x1 = ((sp.x - sp.x % 256) / 256) to x2 = ((sp.x + sp.x % 256) / 256) and from y1 = ((sp.y - sp.y % 256) / 256) to y2 = ((sp.y + sp.y % 256) / 256). It might not be bulletproof (as it is untested), but it should get you an idea of what you need.
The other solution, which probably is not what you really want for a smal-scale project, is to make a quadtree or a kd-tree and make/perform render queries on those. So you probably just want to stick with the first solution :)

Share this post


Link to post
Share on other sites
Yeah, i think i will do the first option. It's not really fancy maths but it would require a bit of thought. Your equations look pretty straight foward.
And btw, that diagram was just to illustrate what i was doing, in reality there would be more tiles than that. As i think i mentioned, the size was 256x256, and my screen will be 800x600 or a bit longer for wide-screen monitors (i will scale up rather that using actual monitor size). So i will have 6 fully visible tiles with at most 20 tiles (fully or partially visible). This is still probably not a problem even on my machine*. And the size will be read from a settings file so the user can change it if need be.

* Laptop, 1.73GHz Pentium M, Intel 915GM/GMS,910GML

Share this post


Link to post
Share on other sites

This topic is 3405 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628633
    • Total Posts
      2983956
  • Similar Content

    • By arash khalaqhdoust
      hey guys i hope you doing all well. last night i released my first game in google app store, i really appreciate you guys  to download it. and share your reviews about it
      the idea of game comes from mini hackgame of Bioshock.
       link of download:
      https://play.google.com/store/apps/details?id=com.RVBinary.piperist
      many thanks
    • By ForgedInteractive
      Who We Are
      We are Forged Interactive, a small team of like-minded game developers with the sole purpose of making games we love! Currently, we're progressing very quickly with our first project and there are plenty of opportunities and work for new interested programmers. With this project, our development platform is Unity 5.5.2 and C# as our behavioral language. Since this project is our first release, the game itself is a smaller project though progress is moving quickly. We are looking to finalize the current project and get started on future projects in the near future and are expanding our team to do so.
       
      Who We Are Looking For:
      Programmer Level Designer  
      About the Game
      Ours is the tale of two siblings, thrown into a world of chaos. Living in the shadow of their parents' heroic deeds and their Uncle's colorful military career, Finn and Atia are about to become the next force to shape our world. How will you rise through the ranks of Hereilla and what will be your legacy? Once defeated your enemies turn coat and join you in your adventures. Players can enjoy a range of troops and abilities based on their gameplay style which become more important as maps introduce more challenging terrain, enemies and bosses. Strong orc knights, dangerous shamans, and even a dragon are out on the prowl. Knowing when to fight and when to run, and how to manage your army is essential. Your actions alone decide the fate of this world.
       
      Previous Work by Team
      Although we are working towards our first game as Forged Interactive, our team members themselves have worked on titles including and not limited to:
      Final Fantasy Kingsglaive FIFA 2017 Xcom 2 Civilization  
      What do we expect?
      Reference work or portfolio. Examples what have you already done and what projects you have worked on academic or otherwise. The ability to commit to the project on a regular basis. If you are going on a two-week trip, we don't mind, but it would be good if you could commit 10+ hours to the project each week. Willingness to work with a royalty based compensation model, you will be paid when the game launches. Openness to learning new tools and techniques
       
      What can we offer?
      Continuous support and availability from our side. You have the ability to give design input, and creative say in the development of the game. Shown in credits on websites, in-game and more. Insight and contacts from within the Industry.
       
      Contact
      If you are interested in knowing more or joining, please email or PM us on Skype. A member of our management team will reply to you within 48 hours.
       
      E-mail: Recruitment@ForgedInteractive.com
      Skype: ForgedInteractive
       
      Regards,
      David, Colin and Joseph
       
      Follow us on:
      Facebook: https://www.facebook.com/ForgedInteractive/
      Twitter: @ForgedInteract
      Youtube: https://www.youtube.com/channel/UCpK3zhq5ToOeDpdI0Eik-Ug?view_as=subscriber
      Reddit: www.reddit.com/user/Forged_Interactive

    • By dell96
      I'm trying to make my first project but I'm stuck i don't know how to make my crate to start to spawn again when i hit the start button after i die.
      hoping someone can help!!!
      Crate.cs
      CrateSpawn.cs
      Cratework.cs
      GameController.cs
      GameManager.cs
    • By Killah Rasta
      Hi!

      I have a complete idea about a 2D top-down, old-school-GTA like gangster game, that have an open world, and where you can build your black empire. I wan't to make it in Unity, but I'm a hobby developer without papers, so I'm open for ideas. I started to build it on the sources from youtube, but actually I would like to contact with a coder and an artist, to build and draw the game together. I don't have ready funds for it, but wan't to make some money by a start-up website, or something like that. I wan't to have two man, that I can trust, share and make a working pre-stage game, that could get some money on a project page and then go on toward to publish!

      Coding jobs: pathfinding (or NavMesh in 3D), AI, cover system, animation and other game mechanisms like fighting, missions, etc.
      Art jobs: buildings, structures, objects inside-outside, characters.
    • By Strifexxx
      Hi guys, check out our new game about sticks. Feedback welcome!
      Download on Google Play: https://play.google.com/store/apps/details?id=com.stickman.destruction.annihilation3
      Youtube: https://www.youtube.com/watch?v=sKF-wBcgo2E
      Stickman Destruction 3 Annihilation  is a sequel to the legendary game of survival, where to make incredible tricks, driving different transport and getting into different crash! The game is made in the best traditions of simulator games with ragdoll physics elements. Make incredible jumps and tricks and destroy the enemy! Your task is make the finish alive or dead!





      Website: http://strifexxx.wixsite.com/cyberpony
      Facebook: https://www.facebook.com/groups/577850349043463/
      VK: https://vk.com/club122273704
  • Popular Now