Jump to content
  • Advertisement
Sign in to follow this  
nooblet

Loading a tiled map

This topic is 2262 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

Hello,

I'm currently working on a top-down shooter, and have reached a "hmm, I'm doing something terribly wrong" point. Basically, here's what I'm trying to accomplish:

  • I'd like to allow the programmer to hard-code in the map (I don't understand how to make a tile editor yet, need to familiarze myself with WPF prior to beginning that project) so that it can be loaded into application for later use. This has been accomplished.
  • After the map has been created, I alter the code so that I can load the map and draw the contents of it. Essentially, if there's a 0 in the text file, draw the grass tile. If there's a 1, draw the dirt tile, etc.
  • I'd like to have mulitple worlds so that if the player goes to a certain location (for instance, they step over the left side of the screen), then the world will change entirely. Think of the old Zelda games.


    The problem is that when I load the text file and draw the world to the screen, I receive extremely bad framerate lag. I've tried altering the source a bit, but now the world doesn't even draw. I've attached a zip that contains the project's code and assets. I'm looking for any type of suggestions with creating and loading tiled maps using C# and XNA. In case you don't wish to download the project, I went ahead and included three source code files which are likely the cause of the issue to this post.

    WARNING: MY SOURCE CODE IS REALLY MESSY AT THE MOMENT! :D

    WorldManager.cs
    [spoiler]
    [source lang="csharp"]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Content;
    using Microsoft.Xna.Framework.Graphics;

    namespace MyGame
    {
    public class WorldManager
    {
    private Vector2[,] worldSize;

    public Vector2[,] WorldSize
    {
    get { return worldSize; }
    set { worldSize = value; }
    }

    public void CreateWorld(string path, string[,] world)
    {
    using (StreamWriter sw = new StreamWriter(path))
    {
    for(int row = 0; row < 19; row++)
    {
    for(int col = 0; col < 25; col++)
    {
    sw.Write(world.GetValue(row, col));
    }

    sw.WriteLine();
    }
    }
    }

    public char[] LoadWorld(string path)
    {
    string data;
    char[] columns;

    using (StreamReader sr = new StreamReader(path))
    {
    data = sr.ReadToEnd();
    columns = data.ToCharArray();
    }

    return columns;
    }
    }
    }
    [/source]
    [/spoiler]

    Grass.cs
    [spoiler]
    [source lang="csharp"]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Content;
    using Microsoft.Xna.Framework.Graphics;

    namespace MyGame
    {
    class Grass : WorldManager
    {
    private string[,] world = new string[19, 25];
    private int y = 0;

    public Texture2D GrassTexture
    {
    get;
    set;
    }

    public void Initialize()
    {
    WorldSize = new Vector2[19, 25];

    for (int row = 0; row < 19; row++)
    {
    y = row * 32;

    for (int col = 0; col < 25; col++)
    {
    WorldSize.SetValue(new Vector2(col * 32, y), row, col);
    Console.WriteLine(WorldSize.GetValue(row, col));
    }
    }
    }

    public void LoadContent(ContentManager Content)
    {
    GrassTexture = Content.Load<Texture2D>("World/Tiles/Grass");
    }

    public void Create()
    {
    for (int row = 0; row < 19; row++)
    {
    for (int col = 0; col < 25; col++)
    {
    world.SetValue("0", row, col);
    }

    Console.WriteLine();
    }

    CreateWorld(@"C:\Games\MyGame\Worlds\GrassWorld.txt", world);
    }

    public void Load(SpriteBatch spriteBatch)
    {
    string path = @"C:\Games\MyGame\Worlds\GrassWorld.txt";

    for (int i = 0; i < LoadWorld(path).Length; i++)
    {
    if(LoadWorld(path) == '0')
    {
    Draw(spriteBatch);
    }
    }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
    for (int row = 0; row < 19; row++)
    {
    for (int col = 0; col < 25; col++)
    {
    spriteBatch.Begin();
    spriteBatch.Draw(GrassTexture, WorldSize[row, col], Color.White);
    spriteBatch.End();
    }
    }
    }
    }
    }
    [/source]
    [/spoiler]

    Game1.cs
    [spoiler]
    [source lang="csharp"]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Audio;
    using Microsoft.Xna.Framework.Content;
    using Microsoft.Xna.Framework.GamerServices;
    using Microsoft.Xna.Framework.Graphics;
    using Microsoft.Xna.Framework.Input;
    using Microsoft.Xna.Framework.Media;

    namespace MyGame
    {
    public class Game1 : Microsoft.Xna.Framework.Game
    {
    public static GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Grass grass = new Grass();

    public Game1()
    {
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
    this.Window.Title = "My Game";

    graphics.PreferredBackBufferWidth = 800;
    graphics.PreferredBackBufferHeight = 600;
    graphics.ApplyChanges();

    Player.Initialize();

    grass.Initialize();

    base.Initialize();
    }

    protected override void LoadContent()
    {
    spriteBatch = new SpriteBatch(GraphicsDevice);

    Player.LoadContent(Content);
    Crosshair.LoadContent(Content);
    grass.LoadContent(Content);
    grass.Load(spriteBatch);
    }

    protected override void UnloadContent()
    {
    }

    protected override void Update(GameTime gameTime)
    {
    InputHandler.Update();
    Crosshair.Update();
    Player.Update();

    base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();

    Player.Draw(spriteBatch);
    Crosshair.Draw(spriteBatch);

    spriteBatch.End();

    base.Draw(gameTime);
    }
    }
    }

    [/source]
    [/spoiler]

Share this post


Link to post
Share on other sites
Advertisement

[background=rgb(250, 251, 252)]Grass.cs[/background]



[color=#282828][font=helvetica, arial, verdana, tahoma, sans-serif]

[background=rgb(250, 251, 252)]
public void Draw(SpriteBatch spriteBatch)
{
for (int row = 0; row < 19; row++)
{
for (int col = 0; col < 25; col++)
{
spriteBatch.Begin();
spriteBatch.Draw(GrassTexture, WorldSize[row, col], Color.White);
spriteBatch.End();
}
}
}
[/background][/font]




Try this instead:

[font=helvetica, arial, verdana, tahoma, sans-serif][size=2][color=#282828]
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
for (int row = 0; row < 19; row++)
{
for (int col = 0; col < 25; col++)
{
spriteBatch.Draw(GrassTexture, WorldSize[row, col], Color.White);
}
}
spriteBatch.End();
}
[/font]


[color=#282828][font=helvetica, arial, verdana, tahoma, sans-serif]

[background=rgb(250, 251, 252)]Or better yet, I don't see where you call grass.Draw() but I'm going to assume it's in Draw() inside Game1.cs (though I only skimmed your code.) If this is the case, just strip the Begin() and End from Grass.Draw to begin with. I assume it works like OpenGL in that it batch's the draw code together so that it only has to draw once. It speeds things up.

Give it a try. ^^

EDIT: ah, I didn't read that your world wasn't drawing. That's because you never call grass.draw().[/background][/font]

Edited by slynk

Share this post


Link to post
Share on other sites
Thanks for your input! If I try the method you recommended (placing spriteBatch.Begin() and .End() before and after the for loop, respectively), then I receive the error:
Begin cannot be called again until End has been successfully called.

If I call grass.Draw() in my Game1.cs after removing spriteBatch.Begin() and .End(), then I receive the following:
Begin must be called successfully before a Draw can be called. Edited by nooblet

Share this post


Link to post
Share on other sites
Did you remove Begin and End from grass or game1? (should remove from grass) and did you place grass.Draw AFTER Begin but BEFORE End just like player.Draw and crosshair.Draw?

Share this post


Link to post
Share on other sites
Removed them from Grass.cs, and I sure did place them after begin but before end. That's why I'm really confused, not sure why it's doing this.

Share this post


Link to post
Share on other sites
It's been a while since I used C#, are objects automatcally passed by ref? You may need to implicitly pass it by ref... seems I remember a ref keyword *shrug*

Share this post


Link to post
Share on other sites
As far as I can tell, you will need to make the following changes:

1) Add a routine for drawing your tiles, and call that from your draw routine.
2) Call the grass draw event from that new routine for any tile object that needs grass drawn on it.
3) remove the spritebatch.begin/end calls in the grass draw routine.
4)remove your grass load procedure. Change it so that you load in tile information from your file and set an enum or property so that you know what tile object needs what type (grass, dirt, whatever you have) then you will 'load' in the type without drawing it. Unless I am much mistaken, you are not going to want to draw your grass when you load the content, only on the draw event.

Slynk is correct in pointing out the draw.begin/end inside of your grass draw loop is causing a lot of your lag.

You are also calling your grass draw routine inside of a loop that calls LoadWorld each time. you call and use loadworld once to find it's length and then again for every single loop in the if statement to see if it is the first time. So if the LoadWorld function returns a char array of length 30, you read the entire file 30 times. Load it once before your loop, and save it. call the saved value instead of the actual function over and over again.

Share this post


Link to post
Share on other sites
in Game.cs



protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);

spriteBatch.Begin();

grass.Draw(spriteBatch);
Player.Draw(spriteBatch);
Crosshair.Draw(spriteBatch);

spriteBatch.End();

base.Draw(gameTime);
}


In Grass.cs




public void Load(SpriteBatch spriteBatch)
{
string path = @"C:\Users\mainuser\Desktop\MyGame\MyGame\Worlds\GrassWorld.txt";
for (int i = 0; i < LoadWorld(path).Length; i++)
{
if(LoadWorld(path) == '0')
{
// >>>> Draw(spriteBatch);
}
}
}

public void Draw(SpriteBatch spriteBatch)
{
for (int row = 0; row < 19; row++)
{
for (int col = 0; col < 25; col++)
{
// spriteBatch.Begin();
spriteBatch.Draw(GrassTexture, WorldSize[row, col], Color.White);
// spriteBatch.End();
}
}
}


This don't fix your code, because the world loading is not well done, but it makes you can call draw in apropiate manner, basically i don't see why you call a Draw function inside one ("Load(SpriteBatch spriteBatch)") that is called at loading time, and don't call it in the loop Draw(...) of game.

i will recomend you that change the load code, in order it fills the world[,] array from .txt file, and then in grass.Draw call spritebatch.Draw with the proper texture depending of tile loaded in world[,].

PD: Sorry by my awfull english, i dont speak english at all. tongue.png Edited by androidedev

Share this post


Link to post
Share on other sites
Thanks for everybody's help and suggestions! I'll see if I can't fix it or find another way of loading a tiled world. Can't find many tutorials and it's very foreign to me. I called it within the load method as I thought the draw method was causing the lag issue (since it was looping the file check every Draw() call. Again, I'll scrap what I have and see if I can't work something different out.

Share this post


Link to post
Share on other sites
If you load the file once in the load process and save it into an object stored in memory it won't have to reach out to the filesystem to read the data every time. It's expensive to read the file each time, so if you store in the load, the draw process won't have to read the file to get the information.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!