unity中获取模型对应的贴图中的像素点,修改颜色

/*
  获取模型对应的贴图中的像素点,修改颜色
*/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DrowLine : MonoBehaviour 
{
    public GameObject m_obj;
    private Texture2D m_tex;
    public Color m_color;
    public int size = 3;
    private Color[] m_textureColorsStart;
    void Start () 
    {
        m_tex = m_obj.GetComponent<MeshRenderer>().material.mainTexture as Texture2D;
        //从纹理中获取像素颜色
        m_textureColorsStart = m_tex.GetPixels();
        Debug.Log(m_tex.name);
    }


    void Update()
    {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Input.GetMouseButton(0))
        {
            if (Physics.Raycast(ray, out hit))
            {
                //在碰撞位置处的UV纹理坐标。
                Vector2 pixelUV = hit.textureCoord;
                //以像素为单位的纹理宽度
                pixelUV.x *= m_tex.width;
                pixelUV.y *= m_tex.height;
                //贴图UV坐标以右上角为原点
                for (float i = pixelUV.x - 1; i < pixelUV.x + size; i++)
                {
                    for (float j = pixelUV.y - 1; j < pixelUV.y + size; j++)
                    {
                        m_tex.SetPixel((int)i, (int)j, m_color);
                    }
                }
                Debug.Log(pixelUV);
                m_tex.Apply();
            }
        }
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            //还原
            m_tex.SetPixels(m_textureColorsStart);
            m_tex.Apply();
        }


        //在处理鼠标按下的记录下位置,抬起的时候记录下位置,取2个位置中间的位置发射射线
        //if (Input.GetMouseButtonDown(0))
        //{
            
        //}
        //if (Input.GetMouseButtonUp(0))
        //{

        //}
    }
}

 

posted @ 2018-07-03 17:09  nanyang0310  阅读(7098)  评论(0编辑  收藏  举报