5.16 貼圖融合

usingUnityEngine;

usingSystem.Collections;

usingSystem.Collections.Generic;

publicclassPlaneScript:MonoBehaviour{

//獲得墻和子彈的紋理圖片

public Texture2D bulletTexture;

public Texture2D wallTexture;

//墻面圖片副本

Texture2D? wallTextureCopy;

//墻面和子彈的寬、高

float wall_width;

float wall_height;

float bullet_width;

float bullet_height;

//獲取射線信息

RaycastHit hit;

//定義一個泛型隊列來存儲像素點信息

Queue <Vector2> uvQueues;

voidStart( ){

uvQueues=new Queue<Vector2>();

//獲取墻面的貼圖

wallTexture=GetComponent<MeshRenderer>.material.mainTexture as Texture2D;

//備份墻面貼圖

wallTextureCopy=Instantiate(wallTexture);

//將備份的材質賦值回去,作為修改的對象

GetComponent<MeshRenderer>( ).material.mainTexture=wallTextureCopy;

wall_height=wallTextureCopy.height;

wall_width=wallTextureCopy.width;

bullet_height=bulletTexture.height;

bullet_width=bulletTexture.width;

}

voidUpdate( ){

//點擊鼠標左鍵發射射線

if(Input.GetMouseButtonDown(0)){

if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),outhit)){

if(hit.collider.name=="Plane"){

Vector2 uv=hit.textureCoord;

uvQueues.Enqueue(uv);//入隊列

//遍歷子彈圖片覆蓋的區域

for(int i=0;i<bullet_width;i++){

for(int j=0;j<bullet_height;i++){

//得到墻面上子彈覆蓋區域對應的每個像素點

float w=uv.x*wall_width-bullet_width/2+i;

float h=uv.y*wall_height-bullet_height/2+j;

//獲得墻上每一個像素點的顏色

Color wallColor=wallTextureCopy.GetPixel((int)w,(int)h);

//子彈對應的每一個像素點的顏色

Color bulletColor=bulletTexture.GetPixel(i,j);

wallTextureCopy.SetPixel((int)w,(int)h,wallColor*bulletColor);

}

}

wallTextureCopy.Apply( );

Invoke("ClearWall",2);//2秒后調用方法,清除墻面上彈痕

}

}

}

}

void ClearWall( ){

//獲取隊列中要取出隊列的信息(彈痕)

Vector2uv=uvQueues.Dequeue( );

for(inti=0;i<bullet_width;i++){

for(intj=0;j<bullet_height;j++){

float w=uv.x*wall_width-bullet_width/2+i;

float h=uv.y*wall_height-bullet_height/2+j;

Color? wallColor=wallTexture.GetPixel((int)w,(int)h);

wallTextureCopy.SetPixel((int)w,(int)h,wallColor);

}

}

wallTextureCopy.Apply();

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容