Hi,
I currently need to find which sprite was hit when for example I have two sprites on top of each other and the top one had a transparent empty area.
I want to point out that this post is not working in my case
http://www.tasharen.com/forum/index.php?topic=7824.0Probably because my sprites are positionned in the world 3D. Here is my current setup:
UIRoot (3D) fixed size, 640
I am currently using the current code to achieve hit detection
void Update()
{
if (!Input.GetMouseButton(0))
return;
RaycastHit hit;
if (!Physics.Raycast(UICamera.mainCamera.camera.ScreenPointToRay(Input.mousePosition), out hit))
return;
UISprite sprite = hit.transform.GetComponent<UISprite>();
Vector3 localHit = hit.transform.InverseTransformPoint(hit.point);
Debug.Log(string.Format("World {0}", hit.point));
Debug.Log(string.Format("Local {0}", localHit));
if (sprite == null)
return;
Texture2D tex = sprite.mainTexture as Texture2D;
UISpriteData data = sprite.atlas.GetSprite(sprite.spriteName);
Debug.Log(string.Format("data {0} {1} {2} {3}", data.x, data.y, data.width, data.height));
Bounds bounds = sprite.CalculateBounds();
Debug.Log(string.Format("Bounds min {0}", bounds.min));
Debug.Log(string.Format("Bounds size {0}", bounds.size));
Vector2 hitLocalUV = Vector2.zero;
// normalize
if (bounds.size.x > 0)
hitLocalUV.x = (localHit.x - bounds.min.x) / (bounds.size.x);
if (bounds.size.y > 0)
hitLocalUV.y = (localHit.y - bounds.min.y) / (bounds.size.y);
Debug.Log(string.Format("hitLocalUV {0}", hitLocalUV));
Texture altasTex = sprite.atlas.texture;
// use scale to to (a.x * b.x) + (a.y * b.y)...
Vector2 hitLocalPixel = hitLocalUV;
hitLocalPixel
.Scale(new Vector2
(data
.width, data
.height)); Debug.Log(string.Format("hitLocalPixel {0}", hitLocalPixel));
Vector2 hitAtlasPixel
= hitLocalPixel
+ new Vector2
(data
.x, data
.y); Debug.Log(string.Format("hitAtlasPixel {0}", hitAtlasPixel));
Color hitPixel = tex.GetPixel(Mathf.RoundToInt(hitAtlasPixel.x), Mathf.RoundToInt(hitAtlasPixel.y));
Debug.Log(string.Format("hitPixel {0}", hitPixel));
}
if I click on a point that should be (348, 1200) on the atlas, I get (348, 1020) for hitAtlasPixel
There only seems to be discrepancy on Y so I was wondering if fixed size could have something to do about it but
root.pixelSizeAdjustment = 1.319588 so the ratio doesn't seem to match my problem
I feel like I am so close of it but i cannot figure it out!
It would be great if you had some tips to give
Thanks you