- Home /
Virtual directional pad
Okay, i'm using now two GUITexture to move my 2D character to left and right and i want to use only one like this image. I want to know how to calculate the axis and when the player finger touchs the right side the character goes to the right, and when he touch the left side than go to the left. i'm coding in C#
Answer by robertbu · Jan 22, 2014 at 12:37 AM
Assuming you setup the pixel inset so that the anchor is at the center, you can just convert the the touch position to Viewport coordinates and subtract the position from them:
var pos = Camera.main.ScreenToViewportPoint(fingerPos);
var pos = pos - transform.position;
'pos' will be relative to the pivot of this texture. Positive 'y' values will be above the pivot, positive 'x' values will be to the right of the pivot.
The pixel inset setup is -57x-57, because the texture is 114x114, i use Transform position to move the GUI texture, should i use pixel inset?
You have it setup correctly. With the two lines of code above, you will have a vector from the pivot to the hit position, and the values will be as I describe.
but and if i press the button on the left but upward, it will not register -x and +y?
You have to figure out what is the do$$anonymous$$ate button pressed. Something like:
if ($$anonymous$$athf.Abs(pos.x) > $$anonymous$$athf.Abs(pos.y)) {
if (pos.x < 0.0) {
Debug.Log("Pressed left arrow");
}
else {
Debug.Log("Pressed right arrow");
}
}
else {
if (pos.y < 0.0) {
Debug.Log("Pressed down arrow");
}
else {
Debug.Log("Pressed up arrow");
}
}
How i never thought about this, thanks man, i think i've been a bit lazy, you are the man!