- Home /
Why does this script work for only one position?
I'm making a game with my team where you drag letters to their correct positions. We have a script made for the correct letters, if the letter is dragged to a certian X and Y range it is suppoed to snap into a position and remain there. In the sample scene (attached file) only one letter works (the "J") while the other correct letter (the "A") doesn't both have the exact same script and have the correct values assigned yet only one letter works. The word is supposed to spell "Abeja" (bee in spanish)
I've even tried making a new scene and assigning those values again but I get the same results only one position works and if I move that correct position it stops working.
The script receives a public Transform variable which is an empty game object and that position is where the correct letter should snap to yet it returns.
Since the sample scene exeeds the aattachment limit you can download it here(1.56MB): https://www.dropbox.com/s/3hbytcht2e9virq/TestScene.unitypackage?dl=0
Any help is highly appreciated.
Answer by sysameca · Nov 18, 2014 at 07:06 AM
Change your Update code like this:
void Update()
{
if (Input.GetMouseButtonUp(0) && hit && movible)
{
if (mover.position.x <= rango.position.x + 1.5 && mover.position.x >= rango.position.x - 1.5)
{
Debug.Log("Letra correcta!");
mover.position = rango.position;
movible = false;
}
else
{
mover.position = posicion;
}
}
}
You are over repeating your code by nesting it which super easy leads to this kind of bugs. My suggestion is when you see you do code like this:
if(mover.position.x<=rango.position.x+1.5 && mover.position.x>=rango.position.x-1.5){
if(mover.position.y<=rango.position.y+1.5 && mover.position.x>=rango.position.y-1.5){
Debug.Log("Letra correcta!");
mover.position=rango.position;
movible = false;
}
else{
mover.position=posicion;
}
}
else{
mover.position=posicion;
}
You need to refactor it at any cost.
Thanks a lot you really helped me. I added an extra bit since that solution only checks for a correct X range so if the height where you drag the correct letter is wrong it will still be marked as correct.
if (Input.Get$$anonymous$$ouseButtonUp(0) && hit && movible)
{
if ((mover.position.x <= rango.position.x + .5 && mover.position.x >= rango.position.x - .5)&&
(mover.position.y <= rango.position.y+.5 && mover.position.y>= rango.position.y-.5))
{
Debug.Log("Letra correcta!");
mover.position = rango.position;
movible = false;
}
else
{
mover.position = posicion;
}
}
Again thanks, we are extremely happy. Thanks to you we will be able to deliver on time!