move object over time on keydown

hello there dear fellow scripters, im totally new to unity coding and coding in general, and now i have run my head into a wall :confused: been searching here for almost 2 hours now and looking at the forums, but poeple use Java…
and i use C# what i want is, i got a flashlight, when i press F i want the flashlight to slide out of view over 1 second,
and then when you click F again i want it to slide back into view how am i to do this in C#? thanks alot in advance!!!

Your problem:

1. check keyboard input?

if (Input.GetKeyDown(KeyCode.F))
//   do the animation 


2. the animation of slide in/out

you need to tell us, hows its going to slide in, left/right/bottom or ?

what you can do is to Lerp or Slerp between two coordinates over time

or, simply open the animation window and build the animation with timeline/keyframes, then attach the animation to the flashlight and play it when needed.


To do the animation, or control it you could implement a state structure.


   bool isFlashShownNow = false;
    bool isFlashGoingToBeShown = false;

   if ((Input.GetKeyDown(KeyCode.F)) && (isFlashGoingToBeShown == isFlashShownNow)   )
      // state is non-animation and we have F pressed...
       isFlashGoingToBeShown = !isFlashGoingToBeShown; // this flips the bool state

   if( isFlashGoingToBeShown != isFlashShownNow )
      // okay, current state and wanted state is not alike, now animate

          // if this is true, then we should animate it to be visible in short time from now...
         flashPos += 1f * Time.deltaTime;
         if (flashPos>100f)
            flashPos = 100f;
            isFlashShownNow = true;
         // oppersite, we are going to hide it...
         flashPos -= 1f * Time.deltaTime;
         if (flashPos<0f)
            flashPos = 0f;
            isFlashShownNow = false;