今天跟大家分享一下自己以前做的一個效果,主要是那時是看到一個外包的要求做的,剛看到外包要求的時候,所要求的技術(shù)自己都寫過,所以基本是有信心完成的,唯獨有一點有點心虛,那就是用戶可以自由定義背景顏色,因為沒有寫過,所以也不知道怎么搞,后來晚上自己立馬想辦法實現(xiàn),那時自己的第一反應就是平時在unity內(nèi)部設置顏色是編輯器提供的顏色選擇,所以自己應用了寫代碼繼承Editor類調(diào)用了,結(jié)果在編輯模式運行的時候是沒有問題的,可是后來發(fā)布出來的時候就是問題了,說什么不記得了,總之就是不能應用Editor類的東東來發(fā)布成應用,這些應該是提供來開發(fā)插件的進行游戲開發(fā)編輯的,至于是不是自己暫時不敢下定論,也可能是自己應用不當,后來自己就到處追尋內(nèi)部API GetPixel來搞,后來也不知道怎么就想到射線檢測了,后來整理了一下想法,自己想出了一個方法,就是通過鼠標單擊(或觸摸點)發(fā)射射線,獲取貼圖上的某點的像素值,因為Texture2D也給我們提供 GetPixel API,同時碰觸會給我們返回這個textureCoord值,也就是圖形學里已經(jīng)經(jīng)過設備坐標化后的紋理坐標。但是要獲取正確的貼圖坐標顏色值,還必須要分別在U、V坐標上乘以貼圖的寬和高(剛開始這個可讓我debug了個夠?。瑫r我們的貼圖必須設置成可讀寫的(默認是不支持的),還有就是貼圖格式設置成RAGB32的。代碼如下:(同時自己也PS合成了一張色彩原理貼圖,共享在我的貼圖相冊)
using UnityEngine;
using System.Collections;
public class ColorSelect : MonoBehaviour {
public Camera cam;
void Start()
{
if(cam == null)
{
cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}
}
void Update ()
{
// Only when we press the mouse
if (Input.touchCount < 1) //應用于手機觸摸版
return;
/*if(!Input.GetMouseButton(0)) //應用于PC或WEB版的鼠標單擊
return;*/
// Only if we hit something, do we continue
//Vector3 TouchPosition = new Vector3(Input.GetTouch(0).position.x,Input.GetTouch(0).position.y,0); //應用鼠標
Vector3 TouchPosition = Input.mousePosition; //觸摸
RaycastHit hit = new RaycastHit();
if (!Physics.Raycast (cam.ScreenPointToRay(TouchPosition),out hit))
return;
// Just in case, also make sure the collider also has a renderer
// material and texture. Also we should ignore primitive colliders.
Renderer renderer = hit.collider.renderer;
if(renderer == null)
return;
//Debug.Log("throught renderer~");
MeshCollider meshCollider = hit.collider as MeshCollider;
if(meshCollider == null)
return;
//Debug.Log("throught mesh collider");
if (renderer.sharedMaterial == null ||
renderer.sharedMaterial.mainTexture == null)
return;
//Debug.Log("done~");
// Now draw a pixel where we hit the object
Texture2D tex = renderer.material.mainTexture as Texture2D;
//Debug.Log("Get Texture:"+tex.name);
Vector2 pixelUV = hit.textureCoord;
//Debug.Log("pixelUV:"+pixelUV);
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
Color color = tex.GetPixel((int)pixelUV.x,(int)pixelUV.y);
//Debug.Log("color:"+color);
cam.backgroundColor = color;
}
}
這只是我個人想到的方法,歡迎交流^_^
在一下的這個鏈接有自己做的demo,里面是用戶可以自定義汽車車身效果
http://www.trusteddivorcelawyers.com/blog/showWork_4985.shtml
免責聲明:本文僅代表作者個人觀點,與納金網(wǎng)無關。其原創(chuàng)性以及文中陳述文字和內(nèi)容未經(jīng)本站證實,對本文以及其中全部或者部分內(nèi)容、文字的真實性、完整性、及時性本站不作任何保證或承諾,請讀者僅作參考,并請自行核實相關內(nèi)容。