2016-10-27 1 views
1

Я пытаюсь создать свой первый игровой движок (в OpenTK и Im застрял. Я пытаюсь включить анимацию, и я пытаюсь использовать спрайты, потому что они значительно уменьшат размер файла.Анимированная анимация Sprite в OpenTK

Я знаю, что мне нужно использовать цикл рисовать все спрайты в последовательности, но я не имею ни малейшего понятия о том, что нужно сделать, чтобы заставить его работать с spritesheets.


Вот мой текущий рисунок код:

//The Basis fuction for all drawing done in the application 
    public static void Draw (Texture2D texture, Vector2 position, Vector2 scale, Color color, Vector2 origin, RectangleF? SourceRec = null) 
    { 
     Vector2[] vertices = new Vector2[4] 
     { 
      new Vector2(0, 0), 
      new Vector2(1, 0), 
      new Vector2(1, 1), 
      new Vector2(0, 1), 
     }; 

     GL.BindTexture(TextureTarget.Texture2D, texture.ID); 

     //Beginning to draw on the screen 
     GL.Begin(PrimitiveType.Quads); 

     GL.Color3(color); 
     for (int i = 0; i < 4; i++) 
     { 

       GL.TexCoord2((SourceRec.Value.Left + vertices[i].X * SourceRec.Value.Width)/texture.Width, (SourceRec.Value.Left + vertices[i].Y * SourceRec.Value.Height)/texture.Height); 

      vertices[i].X *= texture.Width; 
      vertices[i].Y *= texture.Height; 
      vertices[i] -= origin; 
      vertices[i] *= scale; 
      vertices[i] += position; 

      GL.Vertex2(vertices[i]); 
     } 

     GL.End(); 
    } 

    public static void Begin(int screenWidth, int screenHeight) 
    { 
     GL.MatrixMode(MatrixMode.Projection); 
     GL.LoadIdentity(); 
     GL.Ortho(-screenWidth/2, screenWidth/2, screenHeight/2, -screenHeight/2, 0f, 1f); 
    } 

Заранее благодарен! :)

ответ

1

Во-первых, я прошу вас отказаться от контура фиксированной функции. Он ослепляет вас и ограничивает ваше понимание и творчество. Перейдем к ядру 3.1+, его структурное совершенство соответствует только его потенциальности, и совместное предусмотрение и инновации действительно переведут вас.

Теперь вы хотите сохранить изображения ваших спрайтов как Texture2DArray. Потребовалось некоторое время, чтобы выяснить, как они правильно загрузить:

public SpriteSheet(string filename, int spriteWidth, int spriteHeight) 
{ 
    // Assign ID and get name 
    this.textureID = GL.GenTexture(); 
    this.spriteSheetName = Path.GetFileNameWithoutExtension(filename); 

    // Bind the Texture Array and set appropriate parameters 
    GL.BindTexture(TextureTarget.Texture2DArray, textureID); 
    GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); 
    GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); 
    GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); 
    GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); 

    // Load the image file 
    Bitmap image = new Bitmap(@"Tiles/" + filename); 
    BitmapData data = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

    // Determine columns and rows 
    int spriteSheetwidth = image.Width; 
    int spriteSheetheight = image.Height; 
    int columns = spriteSheetwidth/spriteWidth; 
    int rows = spriteSheetheight/spriteHeight; 

    // Allocate storage 
    GL.TexStorage3D(TextureTarget3d.Texture2DArray, 1, SizedInternalFormat.Rgba8, spriteWidth, spriteHeight, rows * columns); 

    // Split the loaded image into individual Texture2D slices 
    GL.PixelStore(PixelStoreParameter.UnpackRowLength, spriteSheetwidth); 
    for (int i = 0; i < columns * rows; i++) 
    { 
     GL.TexSubImage3D(TextureTarget.Texture2DArray, 
         0, 0, 0, i, spriteWidth, spriteHeight, 1, 
         OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, 
         data.Scan0 + (spriteWidth * 4 * (i % columns)) + (spriteSheetwidth * 4 * spriteHeight * (i/columns)));  // 4 bytes in an Bgra value. 
    } 
    image.UnlockBits(data); 
} 

Тогда вы можете просто нарисовать четырехугольник, а Z текстуры координируют является Texture2D индекс в Texture2DArray. Примечание frag_texcoord имеет тип vec3.

#version 330 core 

in vec3 frag_texcoord; 
out vec4 outColor; 

uniform sampler2DArray tex; 

void main() 
{ 
    outColor = texture(tex, vec3(frag_texcoord)); 
} 
+0

Спасибо! Это отлично подойдет для меня, и я буду советоваться не с использованием конвейера с фиксированной функцией. Еще раз спасибо!! –

+0

Ницца, рад сэкономить вам время. –

Смежные вопросы