1
votes

I am developing a simple 3D game with ball. And the ball moves not smoothly.

while (i < Input.touchCount)
        {
            if(Input.GetTouch(i).position.y < ScreenHeight / 2)
            {
                if (Input.GetTouch(i).position.x > ScreenWidth / 2)
                {
                    //move right
                    rigidBody.velocity += new Vector3(0.75f, 0, 0);

                }
                if (Input.GetTouch(i).position.x < ScreenWidth / 2)
                {
                    //move left
                    rigidBody.velocity -= new Vector3(0.75f, 0, 0);

                }
            }
            ++i;
        }

As you can see I used rigid body's velocity and it starts slowly and then goes fast. But I want the ball to move immediately with constant velocity after touching the screen. Also it is moving with jerks, not smoothly. Could you please help me improve it ?

1
If you want it to move at a constant velocity, you should be using regular assignment: = instead of -= and +=. So it would be rigidBody.velocity = new Vector(x,y,z) - Chronicle
And I have to mention that the ball just stays on the spot and moves only in x axis. - Davrick
It's not moving on y axis because the Y value in your vector is 0 - Chronicle
It is worth mentioning that the ball si using a rigidbody, so physics will come into play. All the += and -= on every frame (unless GetTouch is like GetKeyDown) is probably not ideal either as it will continue to accelerate the ball. I suggest doing as @Chronicle says and then maybe go into the rigidbody properties and set the ball as Kinematic, so that outside forces do't interact with it. - LLSv2.0
Hi, @Davrick consider using Lerping in order to make a movement to run smoothly, see docs.unity3d.com/ScriptReference/Vector3.Lerp.html - loic.lopez

1 Answers

0
votes

Keep in mind that physics calculations need to be in the FixedUpdate() event method:

From MonoBehaviour.FixedUpdate()

Frame-rate independent MonoBehaviour.FixedUpdate message for physics calculations.

MonoBehaviour.FixedUpdate has the frequency of the physics system; it is called every fixed frame-rate frame. Compute Physics system calculations after FixedUpdate. 0.02 seconds (50 calls per second) is the default time between calls. Use Time.fixedDeltaTime to access this value.

References:

Hopes it will helps.