[2D] How to check if boxes are aligned in a certain order
If any of you have played Typoman, you'll understand what I mean.
Basically, I want to be able to check if boxes (or letters in my game) are aligned in a certain order. For example, if there are three boxes in a level, a 'K' box, a 'E' box and a 'Y' box, I want to be able to check for when the players correctly spells 'Key' so that I can spawn a key.
I don't want it to just check when all 3 boxes are next to each other, they have to be in order.
I'm fairly new to Unity, so if you could explain it, that would be great, thanks!
Answer by Weetman · May 20, 2017 at 02:35 PM
Hi @IKarmaUK,
I took a look at the aforementioned game Typoman. I have an idea that might (hopefully) help you. Here's how I'd do it:
Create a class for defining the Word to be written by the player. Each level would then have many Words, one for each puzzle.
Through the inspector you can set how many letters the Word has, maybe as an array of instances of your Letter class (or struct).
Create the letters from a prefab and place them where you want them. Drag their reference to the Word script in the Inspector in the correct order.
Each letter has it's own char variable.
You can have variables in the Letter class to set the next and previous letter following the array sequence from the Word class. You'll need to know what the next letter should be (if any), what the previous letter should be (if any) and the distance the other letter should be.
Then, during the game you can cast rays (Physics2d.Raycast) to each side of each Letter (perhaps with a layer mask for hitting the letters only). The Raycast method outputs a RaycastHit2D object, which allows you to check how far away the other letter is and it also has a reference to the collider that got hit.
Every letter object should hit the "Next" Letter object to the right and the Previous Letter object to the left (as set in the array).
You can have a distance variable to check if the other letter is close enough.
This is probably not the best way of doing it, but here's hoping I helped you somehow.
Please let me know