Skip to content

Instantly share code, notes, and snippets.

@ikhanhmai
Created December 29, 2015 02:20
Show Gist options
  • Save ikhanhmai/fccf5aefdb6ba2420278 to your computer and use it in GitHub Desktop.
Save ikhanhmai/fccf5aefdb6ba2420278 to your computer and use it in GitHub Desktop.
Unity - Get transparency of one pixel
using UnityEngine;
using System.Collections;
public class RayCasting : MonoBehaviour {
void Update () {
if (!Input.GetMouseButtonDown(0))
{
return;
}
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll(ray);
Vector3 v;
bool[] transparent = new bool[hits.Length];
for (int i=0; i < hits.Length; i++)
{
Texture2D pic = hits[i].transform.gameObject.renderer.material.mainTexture as Texture2D;
// - Translate the RaycastHit.point to local coordinates of the object
v = hits[i].transform.worldToLocalMatrix.MultiplyPoint(hits[i].point);
// - Translate the coordinates to a UV system (0 to 1) based on the object size.
float xPic = 10 - (v.x + 5);
float yPic = v.y + 5;
// - Use Texture2D.GetPixel() or Texture2D.GetPixelBilinear()
// - Examine the alpha value of the color returned
if(pic.GetPixel((int)((xPic/10)*pic.width),(int)((yPic/10)*pic.height)).a).a < 0.5)
transparent[i] = true; //pixel is transparent
Debug.Log(hits[i].transform);
}
int res = 0;
if(hits.Length != 0)
res = exam(hits, transparent);
//if front checking function found something
//we remove it
if(res != hits.Length)
Destroy(hits[res].transform.gameObject);
}
// function which check, what is on front
int exam(RaycastHit[] hits, bool[] t)
{
float tmp = 100;
int resRay = hits.Length;
for(int i = 0; i < hits.Length; i++)
{
if((hits[i].transform.position.z < tmp) && !t[i])
{
tmp = hits[i].transform.position.z;
resRay = i;
}
}
return resRay;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment