Skip to content

Instantly share code, notes, and snippets.

@huytd
Created March 15, 2014 16:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huytd/9569548 to your computer and use it in GitHub Desktop.
Save huytd/9569548 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class Paint : MonoBehaviour {
Texture2D tex;
// Use this for initialization
void Start () {
tex = new Texture2D(128, 128);
GameObject.Find("Plane").renderer.sharedMaterial.mainTexture = tex;
}
void Update () {
if (tex != null)
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Input.GetButton("Fire1"))
{
if (Physics.Raycast (ray, out hit, Mathf.Infinity))
{
// Find the u,v coordinate of the Texture
Vector2 uv;
uv.x = (hit.point.x - hit.collider.bounds.min.x) / hit.collider.bounds.size.x;
uv.y = (hit.point.y - hit.collider.bounds.min.y) / hit.collider.bounds.size.y;
// Paint it red
tex.SetPixel ((int)(-uv.x * tex.width), (int)(uv.y * tex.height), Color.red);
tex.SetPixel ((int)(-uv.x * tex.width), (int)(uv.y * tex.height) + 1, Color.red);
tex.SetPixel ((int)(-uv.x * tex.width) + 1, (int)(uv.y * tex.height), Color.red);
tex.SetPixel ((int)(-uv.x * tex.width), (int)(uv.y * tex.height) - 1, Color.red);
tex.SetPixel ((int)(-uv.x * tex.width) - 1, (int)(uv.y * tex.height), Color.red);
tex.SetPixel ((int)(-uv.x * tex.width) + 1, (int)(uv.y * tex.height) + 1, Color.red);
tex.SetPixel ((int)(-uv.x * tex.width) - 1, (int)(uv.y * tex.height) - 1, Color.red);
tex.SetPixel ((int)(-uv.x * tex.width) - 1, (int)(uv.y * tex.height) + 1, Color.red);
tex.SetPixel ((int)(-uv.x * tex.width) + 1, (int)(uv.y * tex.height) - 1, Color.red);
tex.Apply ();
}
}
if (Input.GetButton("Fire2"))
{
for (int i = 0; i < 128; i++)
{
for (int j = 0; j < 128; j++)
{
tex.SetPixel(i,j, Color.white);
}
}
tex.Apply();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment