1

I've done a small game with a simple tile engine that draws a sprite corresponding to a number in a .txt file. And now I want to advance, I want to make so the game reads a .png or something and for every pixel it draws a sprite. And with different colors within the image, a different sprite draws. Can some one help me with this? Also, I'm doing this in C# XNA 4.0.

4

2 回答 2

1

首先,使用管道将图像加载到 Texture2D 中。然后在您的代码中使用 texture2d.GetData 来获取像素的颜色。

MSDN texture2d.GetData 示例http://msdn.microsoft.com/en-us/library/bb197093.aspx

于 2012-11-28T17:55:07.757 回答
1

Texture2D.GetData如果您使用它来制作瓦片地图(我假设地图将是瓦片的 2D 网格),使用它可能会很棘手,因为 Texture2D . GetData返回一个一维数组。

首先,您将需要您的地图数组,但是您存储它可能如下所示:

Color[,] tiles = new Color[LEVEL_WIDTH,LEVEL_HEIGHT];

我使用以下技术从文件加载预制结构

//Load the texture from the content pipeline
Texture2D texture = Content.Load<Texture2D>("Your Texture Name and Directory");

//Convert the 1D array, to a 2D array for accessing data easily (Much easier to do Colors[x,y] than Colors[i],because it specifies an easy to read pixel)
Color[,] Colors = TextureTo2DArray(texture);

而且功能...

    Color[,] TextureTo2DArray(Texture2D texture)
    {
        Color[] colors1D = new Color[texture.Width * texture.Height]; //The hard to read,1D array
        texture.GetData(colors1D); //Get the colors and add them to the array

        Color[,] colors2D = new Color[texture.Width, texture.Height]; //The new, easy to read 2D array
        for (int x = 0; x < texture.Width; x++) //Convert!
            for (int y = 0; y < texture.Height; y++)
                colors2D[x, y] = colors1D[x + y * texture.Width];

        return colors2D; //Done!
    }

现在您可能想要将地图设置为颜色,所以只需这样做tiles = Colors,您就可以使用 ! 轻松访问数组中的数据Colors[x,y]

例子:

 using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace YourNameSpace
{
    class Game
    {
        //"Global" array for the map, this holds each tile
        Color[,] tiles = new Color[LEVEL_WIDTH, LEVEL_HEIGHT];
        protected override void Initialize() //OR wherever you load the map and stuff
        {
            //Load the texture from the content pipeline
            Texture2D texture = Content.Load<Texture2D>("Your Texture Name and Directory");

            //Convert the 1D array, to a 2D array for accessing data easily (Much easier to do Colors[x,y] than Colors[i],because it specifies an easy to read pixel)
            Color[,] Colors = TextureTo2DArray(texture);
        }
        Color[,] TextureTo2DArray(Texture2D texture)
        { //ADD THE REST, I REMOVED TO SAVE SPACE
        }
    }
}
于 2012-11-28T21:07:30.300 回答