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<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;
}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值