- Home /
Touch To Move iPhone
I would like a script to move a game object on the x and y axis. I tried to use the DragTransform script in the Standard Assets folder. But it doesn't move with the touch and seems laggy and on top of that it is really hard to touch... maybe iPhone mouse emulation is not very accurate.
Is there a script to do this (on iphone) or a tutorial? If not can I have some pointers on how to do this.
THANKS!!
Answer by Andre-Odendaal · Feb 07, 2011 at 09:05 AM
You can use Input.touches
which returns deltaPosition
for each touch and apply that to your transform.
// C# Code Snippet // Update is called once per frame void Update () { // Only if there are touches if (Input.touches.Length > 0) { // Only work with the first touch // and only if the touch moved since last update if (Input.touches[0].phase == TouchPhase.Moved) { float x = Input.touches[0].deltaPosition.x * speed * Time.deltaTime; float y = Input.touches[0].deltaPosition.y * speed * Time.deltaTime;
transform.Translate(new Vector3(x, y, 0));
}
}
}
and here is a JavaScript code snippet:
// JavaScript Code Snippet function Update () { // Only if there are touches if (Input.touches.Length > 0) { // Only work with the first touch // and only if the touch moved since last update if (Input.touches[0].phase == TouchPhase.Moved) { var x = Input.touches[0].deltaPosition.x * speed * Time.deltaTime; var y = Input.touches[0].deltaPosition.y * speed * Time.deltaTime;
transform.Translate(new Vector3(x, y, 0));
}
}
}
Please note this is just a snippet. If you want to directly copy this code please add a speed variable to your script before running.
It had about 5 errors. -BCE0044: expecting :, found 'x'. -Unexpected token: if. -Unexpected token: if. -UCE0001: ';' expected. Insert a semicolon at the end. -UCE0001: ';' expected. Insert a semicolon at the end.
Oops, I should have mentioned this is a C# code snippet. You also need to declare a speed float if you want to directly copy it.
A'ight,I have a question:I haven't tested this code but reading it a notion struck me, as we move our finger further the x value increases and thus the speed of transform movement, right? so what if we want this : if the touch is on left side of the screen and no matter how lengthy the distance of touch move be but the transform will lerp from 0 speed to a constant speed and stays until touch is canceled...
Answer by Core · Jun 08, 2011 at 05:18 PM
Brilliant! Works like a charm! Thanks Andre!
Please consider marking the answer with the tick icon if it helped you.
Answer by przem997 · Aug 12, 2013 at 07:39 AM
Anywere touch move Object, this must be touch on object then can move... is not?
Your answer
