Moving an object to a predetermined position

Hello, I’m very new to Unity and c#, but I’m trying to learn so sorry if this is a easy fix. I’m trying to move an object to a certain position while being able to control how fast it gets there. I don’t want to have to hold down the key to make the object move either, but rather it be done with a single key press. I’ve tried assigning it a new Vector3 position but my object gets stuck in the ground if I multiply it by speed.

1 Like

Look up Unity - Scripting API: Vector3.MoveTowards

I’ve got what I wanted to happen using a coroutine however I’m unsure how to make the coroutine start when I activate a keypress. I’ve tried putting it before the loop but that didn’t work. Do you know how to make that happen?

1 Like

You probably just want to make it an animation or use a tweener.

If you’re hell-bent on writing code for something so mundane, then…

Smoothing movement between any two particular values:

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: SmoothMovement.cs · GitHub

Another approach would be to use a tweening package such as LeanTween, DOTween or iTween.

OR… just make a simple canned animation… No code needed!

For score count-up (like a cash register whizzing lots of numbers upwards), I like this approach: