C# Smoothing Out transform.Translate

Hi everyone, is there a way to smooth out transform.Translate? I have a script where a gameobject is moved +1 in the y axis transform.Translate(0,1,0); but it feels very jagged and unnatural.

Lerp is a good way to smoothen movements, take a look at the following link for some examples: http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Lerp.html

4 Answers

4

Have a target position rather than changing the transform.position directly and then use an update function to Lerp towards it - or SmoothDamp etc.

#SmoothPosition.cs

   using UnityEngine;

   public class SmoothPosition : MonoBehaviour
   {
          public Vector3 targetPosition;
          public Quaternion targetRotation; //Optional of course
          public float smoothFactor = 2;

          void Update()
          {
                transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smoothFactor);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * smoothFactor);
          }
   }

Then rather than doing transform.position = something:

     gameObject.GetComponent<SmoothPosition>().targetPosition = something;

Though preferably cache it to avoid too many GetComponent calls.

That smooths it way too much and my gameobject doesn't go anywhere.

Did you adjust the smoothing factor?

Yes I did.There seems to be a sort of balance between the smoothing and no smoothing. So far I have seen that if I don't have smooth my gameobject is able to make it to it's destination but it is not very smooth as it's making its way.But if I have the smoothing the object doesn't make it to it's destination.

Well that's odd - I guess it could take a while but should be visually there quickly You could do transform.position = Vector3.MoveTowards(transform.position, targetPosition, maxSpeed); Or use a SmoothDamp

Nope, still doesn't work.

// if youre using left/right key try this

int speed = 10;
transform.Translate(Vector3.left * Input.GetAxis("Horizontal") * speed * Time.deltaTime);

// Input.getaxis() value is 0.0 - 1, it accelerate to 1 if you pressed left/right key and decelerate if released the key.

try to create variable and accelerate and limit its value to 1.

This worked great for me!

Try this

    public Transform target;
    public float speed = 20f;

    void Update() {
        float move = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, target.position, move);
    }