Smother Movement

In the side scrolling game I am currently working on, I;m using a circle shaped object for the player. The way I have the movement now makes the object changed directions too quickly.

GetComponent ().velocity = new Vector2 (-moveSpeed, GetComponent ().velocity.y);

Is there a way (possibly by changing velocity) to make the transitions from left to right more smoothly?

Thanks in advance! :slight_smile:

The right movement is as follows:

GetComponent ().velocity = new Vector2 (moveSpeed, GetComponent ().velocity.y);

Try applying forces instead of directly changing the velocity: Unity - Scripting API: Rigidbody.AddForce

1 Like

There are a bunch of ways. You can replace moveSpeed with a currentMoveSpeed variable that is “moved” towards zero, -moveSpeed, or moveSpeed using Mathf.Lerp. You could, as suggested above, use AddForce instead of setting the velocity directly. But, the easiest way to do this would probably be to use Input.GetAxis(“Horizontal”) * moveSpeed which does this sort of smoothing on its own.

Not related to the question itself: you shouldn’t be using GetComponent so often - it’s slow. Use it once, and cache the result:

Rigidbody2D r2d;
void Start() {
r2d = GetComponent<Rigidbody2D>();
}
void FixedUpdate() {
r2d.velocity = new Vector2(Input.GetAxis("Horizontal") * moveSpeed, r2d.velocity.y);
}
2 Likes

This is awesome thank you! Just one more question… How could I make this go right? :o

Ah I’ve got it! But thank you very much :slight_smile: