C# XNA Random tile engine

不打扰是莪最后的温柔 提交于 2019-12-13 07:12:29

问题


public void Draw(SpriteBatch theSpriteBatch)
    {
        Random rand = new Random();
        for(int y = 0; y < map.GetLength(0); y++) {
            for(int x = 0; x < map.GetLength(1); x++) {
                theSpriteBatch.Draw(tile[rand.Next(0,3)], new Rectangle(x*tileWidth,y*tileHeight,tileWidth,tileHeight), 
                    Color.White);
            }
        }
    }

When I do this it just flickers the tiles and constantly redraws them. What do I do to get the random effect with it only drawing once? Is there a way I could click on these tiles with the mouse and have them change? Also, is there a way to make one tile more prevalent than the others?


回答1:


I believe you are looking to only randomly generate the tiles one time and then draw THAT random sequence every time. Remember, Draw in XNA runs every "frame", which is generally way more than once per second!

Copy your current loops over to a new area: your map loading. Also add a 2D data structure (array or whatever) to store the results of your tile generation. I'm calling my sample 2D integer array tileNums. Now, keep the loops as they are now but change the innards to store the results instead of draw:

    Random rand = new Random();
    for(int y = 0; y < map.GetLength(0); y++) {
        for(int x = 0; x < map.GetLength(1); x++) {
            tileNums[x, y] = rand.Next(0,3);
        }
    }

Now just change the innards of your current Draw loop to no longer generate randomly and instead to take from this data:

    //Random object no longer needed
    for(int y = 0; y < map.GetLength(0); y++) {
        for(int x = 0; x < map.GetLength(1); x++) {
            theSpriteBatch.Draw(tile[tileNums[x, y]], new Rectangle(x*tileWidth,y*tileHeight,tileWidth,tileHeight), 
                Color.White);
        }
    }


来源:https://stackoverflow.com/questions/9460807/c-sharp-xna-random-tile-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!