- Home /
No control over Vector3.SmoothDamp. How do I fix this?
I have this script on a prefab so once it's instantiated, it moves to the preset target. However, I'd like to control the speed of the SmoothDamp but no matter what values I change the smoothTime and smoothSpeed to, it's still the same velocity. However, when I test this code in a new project and use it, the parameters adjust the way that I want. I've double-checked if there was anything that would interfere with my SmoothDamp in my prefab but I can't seem to find anything. Here's the code:
public Transform target;
Vector3 currentVel;
public float smoothTime;
public float smoothSpeed;
// Update is called once per frame
void Start()
{
StartCoroutine("MoveToTarget");
}
IEnumerator MoveToTarget()
{
while (true)
{
if (Vector3.Distance(transform.position, target.position) > 0)
{
if (Vector3.Distance(transform.position, target.position) > 1.0f)
Debug.Log("FINISHED");
transform.position = Vector3.SmoothDamp(transform.position, target.position, ref currentVel, smoothTime, smoothSpeed);
}
else
{
}
yield return new WaitForSeconds(0.01f);
}
}
Answer by A_Lego · Oct 31, 2018 at 06:34 AM
Firstly, you made an infinite loop. I don't know if that was your intention, but I don't recommend doing that.
Secondly, the if statement is checking to see if the values are 1 unit away from eachother but it looks like your trying to move the transform TO the target, so it will only print "FINISHED" whenever it is more than 1 unit away from it's target. It's also going to continue to spam it every 0.01 seconds while it is greater than 1 unit away
Thirdly, it is highly recommended to not do anything taxing within Coroutines as they are not very good at handling high computation. I would recommend doing most of that in your Update method or possible even your FixedUpdate method.
Fourthly, your function is only running every 0.01 seconds, so your SmoothDamp is only being triggered that often.
Other than that, I don't see any issues with your code.
PS. the first note was just a suggestion, I could see uses for the infinite loop but I believe there are better ways to handle that as using the Vector3.Distance function can be a bit taxing on machines.
Your answer
Follow this Question
Related Questions
Using Mathf.SmoothDamp() in a foreach loop 1 Answer
how do i smooth out this movement c# 1 Answer
SmoothDamp smoothTime ignored! 1 Answer