unity3d/用户自由改变背景色

通过鼠标单击(或触摸点)发射射线,获取贴图上的某点的像素值,因为Texture2D也给我们提供 GetPixel API,同时碰触会给我们返回这个textureCoord值,也就是图形学里已经经过设备坐标化后的纹理坐标。但是要获取正确的贴图坐标颜色值,还必须要分别在U、V坐标上乘以贴图的宽和高(刚开始这个可让我debug了个够啊),同时我们的贴图必须设置成可读写的(默认是不支持的),还有就是贴图格式设置成RAGB32的。代码如下:(同时自己也PS合成了一张色彩原理贴图,共享在我的贴图相册)

 
using UnityEngine;
using System.Collections;
 
public class ColorSelect : MonoBehaviour {
public Camera cam;
void Start()
{
if(cam == null)
{
cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent();
}
}
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;
}
}


你可能感兴趣的:(unity3d)