Move gameobject to fixed position and back - Using Keypresses

I have made this build where some components of a Booster pump gets shown like in the image below.
However now they just gets shown/hidden by pressing the “1” key.

It would be cool if i could make them extend smoothly from the assembled position instead.

Could someone help me modify my script to do that?
To extend/move the circled parts smoothly to an fixed position with a keypress and go back when pressing the same key again.

So far I can only make a part keep going in a certain direction, using the speed of my choice, but its a start :slight_smile:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveToPos : MonoBehaviour
{
    Vector3 EndPos;
    Vector3 StartPos;
    public float distPos;
    public float MovSpeed;


    void Start()
    {
        StartPos = transform.position;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.UpArrow))
            EndPos = transform.position + new Vector3 (0, 0, 1) * MovSpeed * Time.deltaTime;

        distPos += 0.01f;
        transform.position = Vector3.Lerp(StartPos, EndPos, distPos);

    }
}

Hi @JesperGreen

There are a few tricks to this, but looking at your code, you perhaps need to consider the “distPos” value and make it Clamp01(…) (Keeps it between 0 and 1) and use the key press to flip the direction. Something like (I’ve just typed this in here, not tested / syntax checked)…

Extra declarations…

float direction = 1f; // The direction of travel
float maxDistance = 2f; // The maximum move distance

Start()
{
  StartPos = transform.position;
  EndPos = StartPos + Vector3.forward * maxDistance;
}

Update()
{
  if (Input.GetKey(KeyCode.UpArrow))
             direction = 1f;
  else
             direction = -1f;

  distPos = Mathf.Clamp01(distPos + (time.deltaTime * moveSpeed * direction));
  transform.position = Vector3.Lerp(StartPos, EndPos, distPos);
}

Hope this helps :slight_smile: