Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Offset Vector2 by another Vector2

Discussion in '2D' started by TheBreadPerson, Jul 10, 2022.

  1. TheBreadPerson

    TheBreadPerson

    Joined:
    Aug 6, 2021
    Posts:
    11
    Code (CSharp):
    1. if(touch.phase == TouchPhase.Moved)
    2.             {
    3.                 if(IsHoldingPlayer)
    4.                 {
    5.                     transform.position = new Vector2(transform.position.x, TouchPos.y);
    6.                 }
    7.             }
    using this code I want to make it so my player moves up and down based off the finger position, but as of now they just teleport to the finger. How do I make it so if the user is touching the top of the screen, and the player is at the bottom, the user can still move the character up and down without teleporting to the finger?
     
  2. TheBreadPerson

    TheBreadPerson

    Joined:
    Aug 6, 2021
    Posts:
    11
    this code is in the update function by the way
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,960
    Two possible approaches with completely different outcomes:

    - treat input as a movement, then update the position each frame based on the movement

    OR

    - use this approach:

    Smoothing movement between any two particular values:

    https://forum.unity.com/threads/beginner-need-help-with-smoothdamp.988959/#post-6430100

    You have currentQuantity and desiredQuantity.
    - only set desiredQuantity
    - the code always moves currentQuantity towards desiredQuantity
    - read currentQuantity for the smoothed value

    Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

    The code: https://gist.github.com/kurtdekker/fb3c33ec6911a1d9bfcb23e9f62adac4