Rendering a picture requires initialization of the SDL Picture library.
Steps to Render an Picture
- Initialize SDL_Image for the asset file sorts you wish to use.
- Load a Texture
- Hold that Texture in an Entity struct that additionally tracks the entity’s place.
-
SDL.RenderCopy()
to attract the entity to the scene earlier thanSDL.RenderPresent()
SDL_Image.Init()
The Picture library extends the core library to permit for utilizing .png photographs once we use the SDL_Image.INIT_PNG
flag.
SDL_Image.LoadTexture()
In instances the place you are rendering for 2d and also you do NOT have to control a picture (aside from resizing and altering place), LoadTexture()
is probably the most environment friendly option to load a picture asset. See https://wiki.libsdl.org/SDL_image/IMG_LoadTexture.
player_texture := SDL_Image.LoadTexture(recreation.renderer, "property/participant.png")
assert(player_texture != nil, SDL.GetErrorString())
SDL_Image.LoadTexture()
will return nil on an error, so it’s a good suggestion to test that earlier than persevering with with our code.
There’s a mistake within the code under, and chances are you’ll not perceive why your participant.png is not loading should you did not use an assert()
right here:
// strive utilizing an assert right here to see the issue:
player_texture := SDL_Image.LoadTexture(recreation.renderer, "/property/participant.png")
Entity :: struct
Entity structs are a easy option to maintain observe of entity positions and their loaded textures which you want for subsequent calls to SDL.RenderCopy()
.
Entity :: struct
{
tex: ^SDL.Texture,
dest: SDL.Rect,
}
Should you’re utilizing a sprite sheet with many sprites, additionally, you will must maintain observe of the supply place of the picture on the sprite sheet:
Entity :: struct
{
tex: ^SDL.Texture,
supply: SDL.Rect,
dest: SDL.Rect,
}
At this level in our code we don’t want to trace a supply as a result of we’re loading the complete picture.
SDL.RenderCopy()
As a result of we’re loading the complete picture, we are able to go nil
to the SDL.RenderCopy()
perform rather than the supply SDL.Rect
struct:
SDL.RenderCopy(recreation.renderer, recreation.participant.tex, nil, &recreation.participant.dest)
SDL.RenderCopy()
is named in spite of everything inputs are dealt with and any updates are made to the participant struct’s place.