Search Unity

How to stop object from teleporting with the touch drag function

Discussion in 'Scripting' started by loobys, Apr 27, 2018.

  1. loobys

    loobys

    Joined:
    Apr 25, 2018
    Posts:
    3
    The point of our script is for the ball to follow our finger when placed on the screen but since its following where ever we place our finger it will teleport to any new location instead of just smoothly going to where are finger is. The code does work, it follows our finger but every time i release my finger and put it back down it will teleport to that new position.

    Code (CSharp):
    1. void Update (){
    2.         if (Input.GetTouch (0).phase == TouchPhase.Moved) {
    3.             Vector2 pos;
    4.             pos = Camera.main.ScreenToWorldPoint (new Vector2 (Input.mousePosition.x, Input.mousePosition.y));
    5.             transform.position = new Vector2 (pos.x, pos.y + 1f);
    6.         }
    7.  
    8.  
    9. }
    10. }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    What you could do is store the position for TouchPhase.Began and MoveTowards it.
    If you stored the 'Moved' position, also, then your code would always have a 'current destination', and the MoveTowards could execute every update loop, regardless of whether there was a change or not. It would also allow smooth movement.

    On another note, if you don't already do so, you should check for touchCount > 0 before you try to get Touch(0). That way you won't get errors.
     
  3. loobys

    loobys

    Joined:
    Apr 25, 2018
    Posts:
    3
    I'm a beginner I know what you are talking about but I don't how to write it out.
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Move the 'pos' variable outside of Update() method.
    When you get the Began phase, use the same code you have there to get the position

    Do not set the transform.position like you are now. Leave that to the next part I'm writing about.

    Then, after the statements that check for Began/Moved, add some code like this:
    Code (csharp):
    1. pos.y + 1f;
    2.  // change '2' to a variable that you can tune in the inspector, to get a speed you like.
    3. transform.position = Vector3.MoveTowards(transform.position, pos, 2 * Time.delta);