Raylib - Inserting Sprite sheets














































Raylib - Inserting Sprite sheets



 Raylib - Creating main character
 Now that we know how to create shapes and how to move the shapes using either key or mouse, so let's discuss about inserting the hero of the game.
  Raylib has a function that can import a picture in the pop up window. This picture is called a sprite sheet. A sprite sheet is an image that consists of several images and/or animations. Combining the small images in one big image improves the game performance, reduces the memory usage ad decreases the loading time of the game.
Here's an example of a sprite sheet : 




To insert this image in our file we use a function of raylib called Texture2D , Rectangle and Vector2.
All of these functions have different properties like height, width, x, y etc. Make sure you the the image downloaded with you. The character is loaded using DrawTextureRec() function and it takes all the functions mentioned above as a input parameter. And when we want to exit the pop up window we should unload the image to save the memory of the computer using UnloadTexture() which uses the name of the Texture2D.

Here's a code for the same :

 
#include"raylib.h"

int main(){
    
    int windowWidth = 800;
    int windowHeight = 500;
    
    InitWindow(windowWidth,windowHeight,"YOUR GAME");
    SetTargetFPS(60);
    
    
    //character import and dimensions
    Texture2D hero = LoadTexture("textures/hero.png");
    
         //dimensions of hero
    Rectangle heroRec;
    heroRec.width = hero.width/8;   //dividing by 8 because there are 8 frames
    heroRec.height = hero.height;
    heroRec.x = 0;
    heroRec.y = 0;
        //position of hero
    Vector2 heroPos;
    heroPos.x = windowWidth/2 - heroRec.width/2;
    heroPos.y = windowHeight/2 - heroRec.height;
    
    
    
    
    while(WindowShouldClose()==false){
         BeginDrawing();
        ClearBackground(WHITE);
        
          //draws the image on the screen 
         DrawTextureRec(hero,heroRec,heroPos,WHITE);
       
        ClearBackground(BLACK);
        EndDrawing();
    }
    UnloadTexture(hero);
    CloseWindow();
}






Comments