Sorry if this has been answered before, but I couldn't find a good solution to it yet.
I'm using C# and SpriteManager 2, and I'm trying to detect if a user clicks on a sprite, and I need to check if one clicks on the pixels themselves, and not just a box collider around the sprite, so basically pixel perfect detection.
I'm currently trying to do something like this, but I just haven't been able to get it 100% working yet, or if I'm doing it correctly:
Vector3 pos = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
Sprite sprite = (Sprite)GetComponent("Sprite");
// check if alpha value is not 0.0, meaning it has a pixel here
if (((Texture2D)renderer.material.mainTexture).GetPixel((int)(sprite.lowerLeftPixel.x + pos.x), (int)(sprite.lowerLeftPixel.y + pos.y)).a > 0.1f)
{
sprite.SetColor(Color.black);
}
else
{
sprite.SetColor(Color.white);
}
Should this work or is there a better way to do this?
contains code that raycasts at an object and gets the color of whatever pixel you're pointing at, and then acts accordingly. You could just check the alpha value of the pixel that you're aiming at, and then go from there.
Here are the two functions you'll find useful as well:
For anyone that's interested, I managed to get it working with SpriteManager 2 by using the following code. It might depend on some particular settings in my project but hopefully someone finds it useful:
public float TheScaleDown;
public float TheScaleUp;
void Start()
{
// Set the scale of the game, the default resolution of your game, so that calculated the mousepositions correctly out of the world positions (when grabbing the pixel from the texture)
TheScaleDown = (float)Screen.width / 1024.0f;
TheScaleUp = 1024.0f / (float)Screen.width;
}
void Update()
{
Sprite sprite = (Sprite)GetComponent("Sprite");
// Check the rect around the sprite, scaled to fit the resolution size, so we can see if the mouse is within it
Rect rect = new Rect(Camera.main.WorldToScreenPoint(transform.position).x, Camera.main.WorldToScreenPoint(transform.position).y - (sprite.height * TheScaleDown), sprite.width * TheScaleDown, sprite.height * TheScaleDown);
// Is the mouse within the sprite rect?
if(rect.Contains(Input.mousePosition))
{
// Yes, check if we are holding the mouse over a pixel
Vector3 checkPos = new Vector3(sprite.lowerLeftPixel.x + ((Input.mousePosition.x - rect.x) * TheScaleUp), (renderer.material.mainTexture.height - 1) - sprite.lowerLeftPixel.y - ((rect.y - Input.mousePosition.y) * TheScaleUp));
Color pixel = ((Texture2D)renderer.material.mainTexture).GetPixel((int)checkPos.x, (int)checkPos.y);
// Is there a non-transparent pixel here?
if (pixel.a >= 0.1f)
{
// Yes! Draw our sprite as black, just as an indication that it worked
sprite.SetColor(Color.black);
}
else
{
// No, draw it normal
sprite.SetColor(Color.white);
}
}
else
{
// No, draw it normal
sprite.SetColor(Color.white);
}
}