Imitating a keyboard

Hi everyone,

I’m a beginner and I’m sure I’m missing something obvious, but my Lerp code does not work the way I want it to. Basically I’m trying to make a little on-screen keyboard, and I’d like to set it up so that when the player hits a key, the key on the screen moves down and then back up. Any advice would be appreciated! I have searched a lot but apparently in the wrong places. :slight_smile:

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

public class MoveKeysDown : MonoBehaviour
{

    public Transform keyDown;
    public Transform keyUp;

    private Transform startPos;
    private Transform endPos;

    void Start()
    {
        startPos = keyUp;
        endPos = keyDown;
    }

    void Update()
    {
      
        if (Input.GetKeyDown("space"))
        {
            Debug.Log("Space key was pressed");
            transform.position = Vector3.MoveTowards(startPos.position, endPos.position, Time.deltaTime);
        }
        
        if (Input.GetKeyUp("space"))
        {
            Debug.Log("Space key was released");
            transform.position = Vector3.MoveTowards(endPos.position, startPos.position, Time.deltaTime);
        }
    }
}

I was making this harder than it needed to be. The keypress takes up so little time that this is all that’s needed to get an animated effect:

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

public class MoveKeysDown : MonoBehaviour
{

    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            transform.Translate(0.0f, -0.7f, 0.0f);
        }
        
        if (Input.GetKeyUp("space"))
        {
            transform.Translate(0.0f, 0.7f, 0.0f);
        }
    }
}

I’d still be curious why my original code didn’t work though! (You know since I’m trying to learn n all :P)