- Home /
Problem is not reproducible or outdated
[MOBILE 2D] Move object relative to finger in x axis
Hi, I have really low experience with unity, and I've been looking everywhere for a solution to this.
How do I make a 2d object move relative to the finger, in smooth and natural way? It sounds like a relatively simple thing to code for me, but I just haven't gotten it right yet.
I've tried my own methods, which were quite bad, and right now I'm using one I found on an old thread over here:
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved && gameStarted)
{
transform.Translate(touch.deltaPosition.x/Screen.width * velocityConstant, 0.0f, 0.0f);
transform.position = new Vector2(Mathf.Clamp(transform.position.x, leftLimit, rightLimit), transform.position.y);
}
}
It gets the job done sometimes, but it's so inconsistent and unpredictable, it really blows the experience of the game I'm trying to make. Sometimes it moves just a small distance, and then the opposite. My first guess was that it was a framerate problem, but FixedUpdate didn't solve it.
Is there anything in particular I could change to this code to make the movement solid and consistent? Please help!
Your help will be greatly appreciated, Thank you!
Answer by grimmdeveloper · Jun 18, 2016 at 08:54 AM
Well Store the position on touchphase start, subtract the current position of the position on touchphase move from the started touch position.
if (Input.touchCount > 0) {
var touch = Input.GetTouch(0);
switch (touch.phase) {
case TouchPhase.Began:
startPos = touch.position;
break;
case TouchPhase.Moved:
distance = touch.position - startPos;
break;
}
}
The distance would then just be applied to the transforms position x.
@grimmdeveloper Thanks! However, How would you go about applying it?
I tried just sum$$anonymous$$g distance.x to transform.position on case TouchPhase.$$anonymous$$oved, but it moved really fast, so I multiplied it by 0.01. The result wasn't excellent, mainly because sometimes when immediately turning my finger the opposite way, the object wouldn't obey until like 1 second after.
I've also tried
transform.translate(distance.x,0f,0f)
, but again, it moved too fast so I multiplied distance.x by a really small number. The result was pretty similar to the other method.
Have I done anything wrong, am I missing something?
Again, thanks for your answer and time!
Follow this Question
Related Questions
Scaling Script? 1 Answer
Game looks different on device compared to Game View 0 Answers
ScoreManager adding more points than wanted? 1 Answer
Duplication Problem. Please help. 2 Answers
Why won't the Score reset? 2 Answers