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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Smoothly slide player object between two points.

Discussion in 'Scripting' started by aceover9, Mar 29, 2017.

  1. aceover9

    aceover9

    Joined:
    Mar 28, 2017
    Posts:
    19
    Hi.

    I made a topic here recently and learned a lot, including how to better state some of the things I'm trying to do.

    I'm looking for one thing here.

    In my current code:


    else if (Input.GetKeyDown(KeyCode.RightShift))
    if (transform.position.z < 0)
    playertrn.Translate(0.0f, 0.0f, 6.0f, Space.World);

    else if (Input.GetKeyDown(KeyCode.RightShift))
    if (transform.position.z > 0)
    playertrn.Translate(0.0f, 0.0f, -6.0f, Space.World);


    The object is snapping immediately to the destination position. I've seen some guides about perhaps using lerps or a pingpong controller or something but I feel like there may be a way to alter the above script so that the object knows to move to that point at a certain speed rather than instantly.

    Any ideas? Thanks.
     
  2. mumbot

    mumbot

    Joined:
    Oct 19, 2012
    Posts:
    86
    This will transition to a new position smoothly.
    Code (CSharp):
    1. Vector3.Lerp(startPos, endPos, 0.01f);
     
  3. aceover9

    aceover9

    Joined:
    Mar 28, 2017
    Posts:
    19
    Thanks! That's great. I'm messing around with it but I'm not exactly sure how to inculcate that code into mine or where it goes. How would I write out the startPos and andPos so they reference the z axis?

    Any further help is appreciated. Thanks!