- Home /
My Touch Movement Script is Not Working Correctly
Im Making 2D game Where you must run away from enemies but i have problem with my movement script It moves only to Up and right i want it to move to left and down too Script:
#pragma strict
public var speed = 0.1F;
function Update() {
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
// Get movement of the finger since last frame
var touchPosition = Input.GetTouch(0).position;
// Move object across XY plane
transform.Translate(touchPosition.x * speed, touchPosition.y * speed, 0);
}
}
Answer by hbalint1 · May 04, 2015 at 11:19 AM
It's because you approached it wrong. The GetTouch(0).position gives back "Screen values" as coordinates. Like your bottom left corner of the device screen is (0,0) and the top right is (Screen.width, Screen.height). So wherever you touch it will always be positive x and y coordinates, that's why you move only right and up. You should store the touch's position on the begin of the movement (TouchPhase.Began), and then you can use the TouchPhase.Moved to determine whether the new coordinates were smaller or larger, than the originals (at he Began). So if the moved (x,y) coordinates are smaller, than the original (x,y) you should move down left. sorry but I can't provide you with code, just with the idea. maybe someone will come and get you one.
Your answer
Follow this Question
Related Questions
Stop Moving When Not Touching Screen? 1 Answer
I Need Help With Mobile Touch Movement. 0 Answers
Move horizontally on touch 0 Answers
Move 2d game object instantly on position of Touch Input. 1 Answer
Object some times goes off screen 0 Answers