Move gameobject at constant speed

I am new to this engine. So I need help in this basic stuff. I read the other similar question but didn’t get satisfactory answers.

Basically I am developing 2D game using tk2d plugin. I want to move my ball constantly on screen.

 float ballMagnitude = rigidbody.velocity.magnitude;
                if (ballMagnitude < VELOCITY)
                {
                    Vector3 ballVelocity = new Vector3(VELOCITY, VELOCITY, 0f);
                    rigidbody.velocity = ballVelocity;
                }

But this code creates problem when ball direction change. So I need help in this stuff.
If you want more detail then I am ready to provide. Thanks for your intention.

After some what research I have following code :

if (!isPaused)
            {
                float ballMagnitude = rigidbody.velocity.magnitude;
                print("ball magnitude : " + ballMagnitude);
                if (ballMagnitude < SPEED)
                {
                    Vector3 ballVelocity = new Vector3(VELOCITY * (Mathf.Abs(rigidbody.velocity.x) / rigidbody.velocity.x), VELOCITY * (Mathf.Abs(rigidbody.velocity.y) / rigidbody.velocity.y), 0f);
                    rigidbody.velocity = ballVelocity;
                }
            }

            if (Input.GetMouseButtonDown(0) && isPaused)
            {
                Vector3 ballVelocity = new Vector3(VELOCITY, VELOCITY, 0f);
                rigidbody.velocity = ballVelocity;
                isPaused = false;
            }

Using this code, the object moves constantly but it show some jerks in its movement. How to reduce this one?

What problems happens when you change direction?

–

1 Answer

1

As I understand from the code you have posted, you always apply velocity in the same direction. Maybe you need to get the direction vector and then apply velocity in that direction.

Yes now you got my problem but I am somewhat new to unity engine. If you guide more in this then it will become more useful to me.

–

I can now able to resolve direction problem but now I am facing another problem that I am mentioned in my edit section.

–

Instead of immediately setting the velocity to new value, increase it gradually. suggest you check Mathf.Lerp

–

If you have small code snippet ready then provide me because present I can't able to judge it.

–