I don't know how to move smoothly an object to a fixed distance.

Hi guys, I’m hoping someone can help me with this problem, I’m trying to move an object on the X axis with the Input.GetKeyDown, increasing or decreasing with 1 unit every press. The only problem I have is that I don’t know how to make it smoothly, like to go automatically from X: 1 to X: 2 and without teleporting of course. I tried with adding force and velocity change but sometimes the object goes alot further than usual.

This is the code i use:

// Necessary variables.
private Rigidbody player_rb;
public float frontSpeed = 5f;
public float sidewaysSpeed = 200f;

void Awake()
{
player_rb = GetComponent<Rigidbody> (); // Getting the rigidbody from the player.

}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.A))
{
transform.Translate (-1f, 0, 0);
}

if (Input.GetKeyDown(KeyCode.D))
{
transform.Translate(1f, 0, 0);
}
}
  1. Use Update(), not FixedUpdate(). FixedUpdate is for rigid bodies.

  2. Multiply the translation amount by Time.deltaTime.

EDIT: Clarification – yes I know you’re using a rigidbody, but as long as you’re using transform.Translate instead of one of the rigidbody helper functions (like MovePosition), then you may as well not be using a rigidbody.

If the rigidbody has Kinematic set and interpolate enabled, you could try using MovePosition either slowly over several fixedupdates until you get to the desired position, or see what it looks like doing it all at once.

You can also try updating transform.position over several updates with MoveTowards

You could also directly set velocity of the rigidbody, and kill the velocity once the object reaches the position.

1 Like

Ty for the answers, i will try.

Now it’s alot better but the problem is that the object im moving moves too fast from one point to another, any tips to resolve this?

Here’s the code:

// Necessary variables.
private Rigidbody player_rb;
public float frontSpeed = 5f;
public float sidewaysSpeed = 200f;

void Awake()
{
player_rb = GetComponent<Rigidbody> (); // Getting the rigidbody from the player.

}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.A))
{
player_rb.MovePosition(transform.position - transform.right * Time.deltaTime * sidewaysSpeed);
}

if (Input.GetKeyDown(KeyCode.D))
{
player_rb.MovePosition(transform.position + transform.right * Time.deltaTime * sidewaysSpeed);
}
}

Firstly, please use code tags . Your pasted code is being cut off.

Secondly, I see you have a sidewaysSpeed value. That’s good. Just multiply that into your transform.right*Time.deltaTime lines. If you want to go slower, use a speed value of 0.5 to halve the speed, etc.

It’s almost perfect, thank you for helping a newby guy like me :smile:.