Tutorial 05 –
使用曲面變換
在這個教程中我們學習如何使用曲面變形,一種可以建立水面、透鏡、紙張甚至即時的變化。我們使用靜態紋理,但你可以渲染你的整個遊戲情境到一個紋理,通過扭曲網格來達到一些很酷的即時特效。
首先包含標頭檔和變數的聲明。
#include <hge.h>
#include <hgedistort.h>
#include <math.h>
HGE *hge = 0;
HTEXTURE tex;
hgeDistortionMesh *dis;
接著我們聲明一些常量。這裡定義網格的數值和位置。
const int nRows=16;
const int nCols=16;
const float meshx=144;
const float meshy=44;
在FrameFunc中需要一些變數。一對用於計時,結束符用來計算位移。
float dt;
static float t=0.0f;
int i, j, col;
現在是關鍵區段。我們計算網格的位移並通過時間流逝來上色。
dt=hge->Timer_GetDelta();
t+=dt;
for(i=0; i<nRows; i++)
for(j=1; j<nCols-1; j++)
{
dis->SetDisplacement(j, i, cosf(t*5+j/2)*15,0,HGEDISP_NODE);
col=int((cosf(t*5+(i+j)/2)+1)*35);
dis->SetColor(j, i, 0xFF<<24 | col<<16 | col<<8 | col);
}
最終我們渲染網格在RenderFunc中:
hge->Gfx_BeginScene();
hge->Gfx_Clear(0);
dis->Render(meshx, meshy);
hge->Gfx_EndScene();
在WinMain中我們載入紋理並初始化網格:
tex=hge->Texture_Load("texture.jpg");
dis=new hgeDistortionMesh(nCols, nRows);
dis->SetTexture(tex);
dis->SetTextureRect(0, 0, 512, 512);
dis->SetBlendMode(BLEND_COLORADD|BLEND_ALPHABLEND|BLEND_ZWRITE);
dis->Clear(0xFF000000);
結束時刪除紋理和網格。
delete dis;
hge->Texture_Free(tex);