Unity target position never stops with Vector3.SmoothDamp

I've integrated Vector3.SmoothDamp method to have a more fluid and native movement between the character and his camera in Unity. The camera movement is perfectly in sync with the character because both uses SmoothDamp to move, but the character sometimes still looking for the final position in the x axes.

How can I fix the problem introduced by SmoothDamp without remove it? The problem seems to be correlated to targetPosition.x which still changes but I'm not sure why because hrxMovement and velocity.x reaches 0:

float movementDuration = 0.3f;
float movementSpeed = 2.5f;

void Run () {
float hrzMovement = Input.GetAxis("Horizontal");
Vector2 velocity = new Vector2(Vector2.right.x * movementSpeed * hrzMovement, body.velocity.y);
Vector3 targetPosition = new Vector3(body.transform.position.x + hrzMovement, body.transform.position.y, body.transform.position.z);

body.transform.position = Vector3.SmoothDamp(body.transform.position, targetPosition, ref transformVelocity, movementDuration);

print("hrzMovement: " + hrzMovement + ", velocity.x: " + velocity.x + ", targetPosition.x: " + targetPosition.x);

if (velocity.x != 0) {
animation.SetBool("isMoving", true);
orientationMovement = velocity.x;
} else {
animation.SetBool("isMoving", false);
}

if (orientationMovement < 0) {
body.transform.localScale = new Vector3(-1, 1, 1);
} else {
body.transform.localScale = new Vector3(1, 1, 1);
}

}


I'm using Pixel Perfect Camera package, I hope this doesn't affect the code.

• How much is movementDuration? – Bálint Oct 19 '17 at 7:13
• I've update the code, i've set it to float movementDuration = 0.3f; – vitto Oct 19 '17 at 7:18
• It looks like you have a Rigidbody2D attached here, but you're moving it by setting its transform.position. This can cause a number of artifacts and performance impacts as the Rigidbody and Transform components fight for control. You may get smoother & more controllable results if you route all movement through the body, either by steering its velocity or by using MovePosition(). I can't say whether that's the root cause without seeing more about what the body is doing & what's affecting it. – DMGregory Oct 19 '17 at 12:18
• Thanks for the advice, there are tons of ways to do the same thing and sometimes video tutorials suggests wrong things for the same lack of information, I'll fix it. – vitto Oct 21 '17 at 18:54

Vector3 targetPosition = new Vector3(body.transform.position.x + hrzMovement, body.transform.position.y, body.transform.position.z);