- Home /
Touch deltaPosition Android
I need to move my object by lets say X = X - 1 when i move my finger approximately for the same distance on screen... I am making something similar to the tetris game so i have a cube i and i want to drag it excactly to where my finger is, is this possible ? At the moment i am doing something like this :
var touchPosition : Vector2 ;
function Update() {
if (touch.phase == TouchPhase.Moved && touch.phase != TouchPhase.Canceled) {
touchPosition.x = touch.deltaPosition.x;
touchPosition.y = touch.deltaPosition.y; // dragging
}
if (touchPosition.x > 0 ) { //
blockScript.MoveHorizontal(1);
}
else if (touchPosition.x < 0) {
blockScript.MoveHorizontal(-1);
}
}
Answer by suribe · Mar 07, 2014 at 10:22 PM
That code looks like it will move 1 or -1 every frame there is some movement. A better approach would probably be to divide the remember the starting touch position, substract current position from it, and divide the difference by the amount of pixels each block has. e.g.
if (touch.phase == TouchPhase.Started) {
initialPosition = touch.position;
} else if (touch.phase == TouchPhase.Moved) {
var delta = (touch.position - initialPosition).x / PIXELS_IN_CUBE;
// You would need a function that sets the position, instead of just moving it 1 or -1
blockScript.SetHorizontal(delta);
}
Sorry the sintax might not be correct, I don't use javascript, but it should give you the general idea. Of course you also have to declare PIXELS_IN_CUBE to the amount of pixels each cube has horizontally, and define the SetHorizontal function to position your piece.
Your answer
![](https://koobas.hobune.stream/wayback/20220613135645im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Drag and Swap two object using touch 0 Answers
Touch - drag different objects 1 Answer
Dragging Camera based on Touch 0 Answers
how create flipping book effect like apple ibook with touch ? 0 Answers
Touch and Drag for Android problem 0 Answers