- Home /
2 Buttons on Android
Hello, I have 2 virtual buttons on my Android phone screen. Suppose the names are button A and button B.
What I want is: When I touch button A, only function A should be executed. And when I touch button B, only function B should be executed.
The problem is: When I touched button A, both function A and B were executed. Same thing was happened when I touched button B.
My code:
Button_A.js (attached to Button A):
private var latched = false;
function Update () { if (Input.touchCount > 0) { var touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Stationary) { latched = true; } if(touch.phase == TouchPhase.Ended) { latched = false; } } if (latched) { Function_A(); } }
Button_B.js (attached to Button B):
(similar to ButtonA.js, but this executes Function B)
What is wrong with my code?
Answer by syclamoth · May 13, 2012 at 07:35 AM
Problem is- neither of these functions check the position of the touch! You need to add something in the script that checks a position on the screen- try adding something like this:
// at the top
public var buttonPos : Rect; // This is the position of the button on the screen
... in the Update part-
if(buttonPos.Contains(touch.position))
{
// do stuff
}
Thanks, you're right. Sorry for the late reply. How can I know the right x, y, w, & h for the Rect?
You just have to know? I can't tell you the exact dimensions of the button you want, that's like telling me to draw you without having ever seen your face!
Suppose I draw a Rect with Rect(0, 0, 10, 10). How can I view it on the Unity editor Game simulation window? Because it doesn't have color
Answer by rutter · May 13, 2012 at 07:36 AM
It looks like you're checking whether the user is touching, but not where (or what) they are touching. As a result, both buttons see that the user is touching, and both functions are called.
I assume these buttons are objects in your scene? You can use the screen position of the user's touch to send a raycast out from the camera to identify the collider the user is effectively touching.
You can probably find quite a few tutorials on doing exactly this. Once you've resolved a screen position, it's roughly the same problem as "what did the user click on?", which is how most people phrase the question. Most likely you'll be using Camera.ScreenPointToRay() and Physics.Raycast().
Thanks. Yes, the buttons are GameObjects, not GUITextures. Sorry for the late reply. Could you show me how to use the screen position to identify the collider the user is touching? Or can you give me links to the tutorials?
Your answer
Follow this Question
Related Questions
Android touch is not dynamic 1 Answer
android touch input 1 Answer
Unity 2D Mobile Game Drawing Mechanic 0 Answers
Converting screen coordinates to world coordinates 1 Answer
Executing Code Once Per Touch 1 Answer