Slowing down speed value from a specific distance while using Lerp

Hi

I am moving a certain object to the target with a certain speed using Coroutine.

What I want is for the object to slow down when it comes to a certain distance from the target, but still reach the target.

I used this code. However, I could not implement the speed value into this code. It is not working correctly.


(smoothEndDistance value is 5)
(speed value is 15)
(target position is 20 units away)

My goal is to ensure that the game object always stops at the same speed at different movement speed and stopping threshold values.

I’m using the speed value here.

I tried other resources on the internet but they didn’t work.
Many thanks for any help.

Did you try a tweening package like DOTween or LeanTween? They do exactly this:

Like… the above sentence ^ ^ ^ ^ is basically the answer to “What is a tweening package?”

No sense writing code you don’t have to… but if you want to write code, go nuts.

Just know that photographs of code are NOT A THING.

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

If you want to figure out what your code is doing, use this approach:

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

Hi,

Years ago, you wrote something for this feature that I wanted. However, I could not integrate what you wrote into my code.

https://discussions.unity.com/t/668833

With Tween, I can only achieve this with ease type, right?
I’m trying to make a more dynamic system. Because the value that will start slowing down the gameobject will constantly change.

You can write an entire game using tweeners and never move a single object yourself.

I don’t want to use Tween asset. It doesnt fit my script. I just need to implement “current speed” and “remaning distance” paremeters or something else to here:

float distance2 = Vector3.Distance(go.transform.position, TargetPosition.Value);

                    if (distance2 < 5.0f)
                    {
                       speed = Mathf.MoveTowards(remainingDistance, 0.0f, Time.deltaTime);
                    }

For an example, when i added this line (* 2.5f) to this code, it works great and it stops smooth. (if my projectile speed is 15)

float distance2 = Vector3.Distance(go.transform.position, TargetPosition.Value);

                    if (distance2 < 5.0f)
                    {
                        speed = Mathf.MoveTowards(remainingDistance * 2.5f, 0.0f, Time.deltaTime);
                    }

with *2.5f: ( speed is 15)
8367192--1102356--Animation.gif
without *2.5f: ( speed is 15)
8359842--1100535--Animation2.gif

However, When i change the projectile speed, it doesn’t stop smooth again.

with *2.5f: ( speed is 5)
8359842--1100538--Animation3.gif

So I need to change this *2.5f value dynamically. But I don’t know how…

My whole Coroutine:

 public IEnumerator GotoPosition()
        {
            var go = Fsm.GetOwnerDefaultTarget(gameObject);
            Vector3 startPosition = go.transform.position;
            Vector2 Noise = new Vector2(Random.Range(MinNoise.x, MaxNoise.x), Random.Range(MinNoise.y, MaxNoise.y));
            Vector3 BulletDirectionVector = new Vector3(TargetPosition.Value.x, TargetPosition.Value.y + yOffset, TargetPosition.Value.z) - startPosition;
            Vector3 HorizontalNoiseVector = Vector3.Cross(BulletDirectionVector, Vector3.up).normalized;
            float distance = Vector3.Distance(go.transform.position, TargetPosition.Value);
            float remainingDistance = distance;

           

            while (remainingDistance > disableFollowDistance)
            {
                if (smoothEnd.Value)
                {

                    float distance2 = Vector3.Distance(go.transform.position, TargetPosition.Value);

                    if (distance2 < smoothEndDistance)
                    {
                        speed = Mathf.MoveTowards(remainingDistance * 2.5f, 0.0f, Time.deltaTime);
                    }
                    else
                    {
                        speed = MoveSpeed.Value;
                    }
                }
                   
                NoisePosition = NoiseCurve.curve.Evaluate(1 - (remainingDistance / distance));

                if (followTargetBool)
                {
                    if (useCurve)
                    {
                        go.transform.position = Vector3.Lerp(startPosition, TargetPosition.Value + new Vector3(0, yOffset, 0), 1 - (remainingDistance / distance)) + new Vector3(HorizontalNoiseVector.x * NoisePosition * Noise.x, NoisePosition * Noise.y, NoisePosition * HorizontalNoiseVector.z * Noise.x);
                    }
                    else
                    {
                        go.transform.position = Vector3.Lerp(startPosition, TargetPosition.Value + new Vector3(0, yOffset, 0), 1 - (remainingDistance / distance));
                    }
               

                    lookVector = (lastPosition - go.transform.position).normalized / Time.fixedDeltaTime;
                    lastPosition = go.transform.position;
                    go.transform.rotation = Quaternion.LookRotation(-lookVector);
                }
                else
                {
                    if (useCurve)
                    {
                        go.transform.position = Vector3.Lerp(startPosition, reachPos + new Vector3(0, yOffset, 0), 1 - (remainingDistance / distance)) + new Vector3(HorizontalNoiseVector.x * NoisePosition * Noise.x, NoisePosition * Noise.y, NoisePosition * HorizontalNoiseVector.z * Noise.x);
                    }
                    else
                    {
                        go.transform.position = Vector3.Lerp(startPosition, reachPos + new Vector3(0, yOffset, 0), 1 - (remainingDistance / distance));
                    }
                   

                    lookVector = (lastPosition - go.transform.position).normalized / Time.fixedDeltaTime;
                    lastPosition = go.transform.position;
                    go.transform.rotation = Quaternion.LookRotation(-lookVector);

                }

                remainingDistance -= speed * Time.deltaTime;
                yield return null;


            }


            stopCurrent();

        }

Bump

Then don’t use it.

Just know that 100% of what you want to do can be found inside any good Tween asset.

One approach is to go study the tweening packages and see what they do, then replicate it in your code.

If that approach is unsuitable, I don’t see how a bunch of random text typed in this little tiny box will be any more useful.

The final one that doesn’t stop smooth is because you did not change your lerp by value. So your speed changed by some percentage yes?
Then so should have your lerp value been scaled to that percentage.

If your speed doubled then your lerp halfed? Or is it the other way around? Give it a try

looks good in all cases however very nice indeed infact. Well done.

The lerping code is always the same. I’m just changing the speed value.
My speed value is dynamic. It always changes according to the player level.