Pascal遊戲開發入門(二):渲染圖片

Pascal遊戲開發入門(二):渲染圖片

渲染靜態圖片

新增一個Texture,然後Render出來 創建Texture,並獲取尺寸

procedure TGame.Init(title: string; x, y, h, w, flags: integer);
begin
  .....

  pt := IMG_LoadTexture(pr, 'assets/run.png');

  SDL_QueryTexture(pt, nil, nil, @srcRect.w, @srcRect.h);
  destRect.x := srcRect.x;
  destRect.y := srcRect.y;
  destRect.w := srcRect.w;
  destRect.h := srcRect.h;

  ......
end;  

渲染出來

procedure TGame.Render();
begin
  SDL_SetRenderDrawColor(pr, 238, 238, 238, 255);
  SDL_RenderClear(pr);
  
  SDL_RenderCopy(pr, pt, @srcRect, @destRect);

  SDL_RenderPresent(pr);
end; 

渲染動畫

渲染動畫就就快速交替渲染多張圖片

procedure TGame.Update();
begin
  srcRect.x := 96 * (round(SDL_GetTicks() / 100) mod 8);
end;

動畫反轉

本例中,如果人物需要朝相反方向行走,不用再搞一套素材

SDL_RenderCopyEx(pr, pt, @srcRect, @destRect,0, nil, SDL_FLIP_HORIZONTAL);

代碼整理

代碼味道

  • Texture有多個,不能簡單的使用變量。要有一個Texture容器
  • 渲染時的Rect要和Texture的Render在一起防止錯亂

新增一個TextureManager來統一的管理Texture,並解決以上兩個問題

type
  TTextureDict = specialize TFPGMap<string, PSDL_Texture>;

  TTextureManager = class
  private
    textureMap: TTextureDict;
  public
    destructor Destroy();
    function Load(filename: string; id: string; pr: PSDL_Renderer): boolean;
    procedure Draw(id: string; x, y, w, h: integer; pr: PSDL_Renderer;
      flip: integer = 0);
    procedure DrawFrame(id: string; x, y, w, h, row, frame: integer;
      pr: PSDL_Renderer; flip: integer = 0);
  end;

由於多個TextureManager是不合適的 所以改爲單例模式

private
constructor Init;
public
    class function Instance: TTextureManager;

完整代碼見 [https://gitee.com/tom-cat/sdl-hello/tree/v2.0/]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章