Smooth Movement using transform for fixed movement amount?

Updated on February 22, 2018 in Answers
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on February 12, 2018

Basically I have a block I want to move 2 grid spaces when a key is pressed and it is working as intended but its not smooth i.e. it jumps position. So how can I get it smooth without setting a start and end point?

My current code

  1. public void Update()
  2. {
  3. if (Input.GetKeyUp(KeyCode.RightArrow))
  4. {
  5. transform.position += new Vector3(2, 0, 0);
  6. }
  7. }

Thanks in Advance for any hep or ideas

 

🙂

  • Liked by
Reply
0 on February 12, 2018

Use Vector3.Lerp();

transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime);

This will take about 1 second to move completely.

You will need to make a small adjustment to your code for any smooth movement to work.

 

something like this:

Vector3 targetPos;
 
void Start()
{
    targetPos = transform.Position; // So we don't start moving instantly
}
 
void Update()
{
    if (Input.GetKeyUp(KeyCode.RightArrow))
    {
        targetPos = transform.position + (Vector3.right * 2);
    }
 
    if(Vector3.Distance(transform.position, targetPos) > 0) // if we are more than 0 units away
    {
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime);
    }
}
  • Liked by
Reply
Cancel