Frontmost
For those just interested in the Frontmost Sprite Clicker for Unity script, see our javascript code or its C# translation by Enrico Trudu.
Check out Chris’ latest test drawing for the game (click the pic to enlarge) which is inspired by the topic of this post - Linecasting in Unity.
I’ve written a script that solves a huge problem some people have been having in Unity with clicking on 2D sprites and letting Unity know which sprites have been clicked.
The problem is that Unity’s mouse clicks suck baws. Maybe they’re great for some people, but after a year of working with nice and easy Actionscript 3 mouse clicks, coding mouse clicks in Unity feels like some kind of special punishment.
They suck even more when you are working in 2D. Unity 4.3 has new sorting layers that organise sprite depth for you. If you’ve got overlapping sprites it just seems to pick one at random instead of the frontmost sprite.
If a lot of mouse clicking is required in your game, raycasting seems to be the best option. Raycasting (or Linecasting as I’ve used) is like firing an invisible little laser beam from the cursor into another point in the screen and getting information about what it hits. Or like casting out a fishing line…
My linecast was hitting sprites just fine, but whenever sprites overlapped using those handy dandy new sorting layers it kept giving me the background instead of the player I was trying to click on. I’m reluctant to post a screenshot of my test artwork but I’ll just do it to illustrate. Don’t laugh:

I wanted to click on the smiley face in the middle, but the computer thought I wanted the background. So I tried using a function called LinecastAll, which gives you everything underneath the click in a swanky little array. So clicking on the face gave me the face and the background. Swell, I thought, I’ll just take the first result…
Balls again: LinecastAll’s swanky little array is organised any old way. The correct order isn’t guaranteed.
It took me 3 days and nights to figure out this solution and it’s probably optimised like a slug because I was just trying to get the thing working any way I could, so if there’s anything that can be improved feel free to do it or let me know about it via email and I’ll update the code. Also for more future handy scripts follow us on Tumblr. That link again: http://pastebin.com/Vbzrt0z7 . Hope it helps some people out there, I was so frustrated I was ready to put my face right through this screen.
But on a positive note: if I hadn’t written this code I wouldn’t have realised how much I love the word “frontmost” because it’s such a queer sounding word. If you roll the r’s and really pronounce the t’s you get the most out of it.
Frrrrrontmost.
Romano












