- Home /
The question is answered, right answer was accepted
How to continuously detect the exact location of a touch on Android?
Hello Unity Community!
I'm working on a 2D Android game, and I'm having a bit of trouble detecting touches. What I'm trying to do is something along the lines of this:
while(touch.position.x>Screen.width/2)
{
MoveRight();
}
I need this to be continuous, i.e. as long as the right side of the screen has a touch on it, keep moving the character.
I've tried modifying a Unity example, but it didn't work out as expected.
So, my questions:
How is the proper way to do this?
Does it matter if the code is in Update() or FixedUpdate()? I'm using 2D Physics.
Does Unity Remote affect in any way touch detection ?
Answer by pstreef · Jun 17, 2014 at 01:19 PM
1 I would try something like the example below
2 Using Update is better for input, because it is called every frame. FixedUpdate is for physics stuff. (read up on it here)
3 Not as far as I know.
public float movementSpeed = 1.0f;
void Update()
{
if(Input.touches.Length() > 0)
{
Touch touch = Input.touches[0];
if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
{
if(touch.position.x>Screen.width/2)
{
Vector3 oldPos = transform.position;
float newXPos = oldPos.x + movementSpeed * Time.DeltaTime;
transform.position = new Vector3(newXPos,oldPos.y,oldPos.z);
}
}
}
}
Thank you for your great answer. This seems to work very well, except for the fact that I'm getting a "IndexOutOfRangeException: Array index is out of range." error on the Touch touch = Input.touches[0];
line. Any idea what's up with that ?
Yes, I changed the answer with a fix. Not sure if the syntax is 100% correct, but the idea should work. The problem was when there is no touches the Input.touches array has a length of 0 so index 0 is out of range.
Follow this Question
Related Questions
I Need Help With Mobile Touch Movement. 0 Answers
Best way to do touch in with Unity2D? 0 Answers
Please can someone explain how i use the joystick prefab for 2d. 0 Answers
Move horizontally on touch 0 Answers