Hello, Unity Forums! I recently read a tutorial about linear interpolation and decided to use it in my script. I am attempting to make a sphere move around with my arrow keys, but I do not want an abrupt stop motion. When I let go of the key, I want the sphere to ease out slowly, coming to a complete stop. This is currently my script: Code (CSharp): void Update () { if (Input.GetKey (KeyCode.UpArrow)) { transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime); if (Input.GetKeyUp (KeyCode.UpArrow)) transform.Translate = Vector3.Lerp(transform.position.z, transform.position.z * 10f, 0.5f); } I am getting 3 errors: error CS1502: The best overloaded method match for `UnityEngine.Vector3.Lerp(UnityEngine.Vector3, UnityEngine.Vector3, float)' has some invalid arguments error CS1503: Argument `#1' cannot convert `float' expression to type `UnityEngine.Vector3' error CS0131:The left-hand side of an assignment must be a variable, a property or an indexer I don't know if I should use Vector3.Lerp or Mathf.Lerp, or if I'm just not achieving my goal with the appropriate function. The errors aren't helping, either. Could someone help me with this problem(s) please?
Vector3.Lerp lerps vectors, Mathf.Lerp lerps floats. position.z is a float Which do you think you'd use?
Okay, I changed it from Vector3.Lerp to Mathf.Lerp, and only have one error: error CS0131:The left-hand side of an assignment must be a variable, a property or an indexer What do I do now?
What are you even attempting to do? Because this code is just moving in a direction while 'UpArrow' is held, and then on the one frame that it's released, you lerp the z position half of 10 units forward. But you attempt to set that to Translate... You mention that you don't want abrupt stopping. This code is NOT how you do that.
You could do something like this: Code (csharp): private Vector3 _move; void Update() { if(Input.GetKey(KeyCode.UpArrow)) { _move = Vector3.forward * moveSpeed; transform.Translate(_move * Time.deltaTime); } else if(_move.sqrMagnitude > 0f) { //ease out _move *= 0.5f; transform.Translate(_move * Time.deltaTime); //once we've reached a slow enough speed, zero out if(_move.magnitude < 0.01f) _move = Vector3.zero; } }
Dude, thanks so much! I have to go over the code a few times to understand it better (I'm starting with Unity again), but you solved my problem! P.S. One question: How can I increase the ease out time?
I know it's like four years ago, but why not, right? This code halves the movement speed each frame. If you want to make it ease out slower, multiply by a higher number but not higher than one (that would keep accelerating the object), something like 0.75f. The opposite applies too, but make sure you don't go below zero.