做 2D 遊戲時經常需要把素材左右翻轉,最典型的就是角色朝向:原本朝右的人物圖,翻一下就變成朝左,省下另外畫一套素材的功夫。以下提供兩個版本的實作,思路一次比一次精簡。
版本一:先申請暫存記憶體
這個版本把翻轉結果寫入另一組陣列,再複製回來源,邏輯最直白,適合除錯時逐步檢查。
[cpp]
- #include <string.h>
- int flip_horizontal(
- int img_width,
- int img_hight,
- unsigned char *in_red,//傳入的紅色
- unsigned char *in_green,//傳入的綠色
- unsigned char *in_blue,//傳入的藍色
- unsigned char *in_alpha//傳入的透明度
- )
- //水平翻轉圖像
- {
- int x,y,pos,temp;
- unsigned char *out_red;//傳出的紅色
- unsigned char *out_green;//傳出的綠色
- unsigned char *out_blue;//傳出的藍色
- unsigned char *out_alpha;//傳出的透明度
-
- out_red = (unsigned char*)malloc(img_width*img_hight);//申請內存
- out_green = (unsigned char*)malloc(img_width*img_hight);
- out_blue = (unsigned char*)malloc(img_width*img_hight);
- out_alpha = (unsigned char*)malloc(img_width*img_hight);
-
- temp = 0;
-
- for (y=0;y<img_hight;y++) {//y的初始值為0,小於圖片的高度,y自增
- //y表示的是圖片第幾行
- pos = y*img_width + img_width-1;
- for (x=0;x<img_width;x++) {
- out_red[pos] = in_red[temp];
- out_green[pos] = in_green[temp];
- out_blue[pos] = in_blue[temp];
- out_alpha[pos] = in_alpha[temp];
- ++temp;
- --pos;
- //假設img_width = 10,當y=0時,那麼,out_red[9] = in_red[0],以此類推
- //當y=1時,out_red[19] = in_red[10],以此類推
- //把圖片的每一行水平翻轉
- }
- }
- memcpy(in_red,out_red,img_width*img_hight);//拷貝
- memcpy(in_green,out_green,img_width*img_hight);
- memcpy(in_blue,out_blue,img_width*img_hight);
- memcpy(in_alpha,out_alpha,img_width*img_hight);
- free(out_red);
- free(out_blue);//釋放內存
- free(out_green);
- free(out_alpha);
- return 0;
- }
版本二:原地交換,不必額外配置記憶體
後來想通了:水平翻轉本質上就是把每一行左右對稱的像素互換,既然如此,根本不需要再配置一整組暫存陣列。改寫後如下,同時把命中判定與攻擊判定這兩張點陣圖一起翻轉,並在開頭檢查記憶體是否配置成功。
[cpp]
- #include "game_data.h"
- int flip_horizontal(Action_Graph *src)
- /* 將圖像進行水平翻轉 */
- int width = src->width,hight = src->height;
- unsigned char buff;
- if(src->malloc != IS_TRUE){
- value = -1;
- }
- else{
- temp = (int)width/2;
- for (y=0;y<hight;y++) {
- /* 水平翻轉其實也就是交換兩邊的數據 */
- pos = y*img_width;
- for (x=0;x<temp;x++) {
- count = img_width - x - 1;
- buff = src->rgba[0][pos+x];
- src->rgba[0][pos+x] = src->rgba[0][count];
- src->rgba[0][count] = buff;
-
- buff = src->rgba[1][pos+x];
- src->rgba[1][pos+x] = src->rgba[1][count];
- src->rgba[1][count] = buff;
-
- buff = src->rgba[2][pos+x];
- src->rgba[2][pos+x] = src->rgba[2][count];
- src->rgba[2][count] = buff;
-
- buff = src->rgba[3][pos+x];
- src->rgba[3][pos+x] = src->rgba[3][count];
- src->rgba[3][count] = buff;
-
- /* 「命中」點陣圖的翻轉 */
- if(src->hit_flag == IS_TRUE){
- buff = src->hit[pos+x];
- src->hit[pos+x] = src->hit[count];
- src->hit[count] = buff;
- }
- /* 「攻擊」點陣圖的翻轉 */
- if(src->atk_flag == IS_TRUE){
- buff = src->atk[pos+x];
- src->atk[pos+x] = src->atk[count];
- src->atk[count] = buff;
- }
- }
- }
- }
- return value;
- }
由於目前的遊戲需要處理攻擊與被攻擊的判定,我為每一幀圖形都加上了攻擊與被攻擊的點陣圖,翻轉時必須同步處理,否則判定範圍會與畫面錯位——這是改寫這段程式時最容易忽略的一點。