# How do i stop a ball from getting stuck?

Hey guys, im making a game like pong but sometimes when im testing it the ball gets stuck by that i mean it keeps bouncing up and down in the exact same spot is there any way to prevent this from happening here is my script

``````#pragma strict

var cSpeed:float = 10.0;
var sFactor:float = 10.0;
static var playerScore:int = 0;
static var enemyScore:int = 0;

function Start ()
{
}

function Update ()
{
var cvel = rigidbody.velocity;
var tvel = cvel.normalized * cSpeed;
rigidbody.velocity = Vector3.Lerp(cvel,tvel,Time.deltaTime * sFactor);

if(transform.position.x > 23)
{
playerScore++;
transform.position.x = 0;
transform.position.y = 0;
}
if(transform.position.x < -23)
{
enemyScore++;
transform.position.x = 0;
transform.position.y = 0;
}
}
``````

depending on which axis is the one where it gets stuck just be sure that the value is never 0 and if it is 0 just give it little nudge. for example if it gets stuck bouncing along the X-axis while Y-axis is 0 then add like 0.5 to the Y-axis movement

Edit: up on looking at your code I see that it would get stuck when the X- axis movement is 0 so you would have to add some movement to the X axis not vice versa

As a hack you can do something like this:

``````var dot = Vector3.Dot(rigidbody.velocity.normalized, Vector3.up);
if (dot > 0.98 || dot < -0.98) {
var v = Random.insideUnitCircle * factor;
rigidbody.velocity += v;
}
``````

This detects when the ball movement is nearly vertical and then introduces a bit of random change. ‘factor’ is a variable you declare or constant you insert. You’ll have to play to get the value right. This could be put inside FixedUpdate(), but the random movement would be better hidden if you were to only make the change during a collision (i.e. inside OnCollisionEnter() OR OnCollisionExit()).

rigidbody.velocity = Vector3.Lerp(cvel,tvel,Time.deltaTime * sFactor);

dont do this

rigidbodies are for physics calculations.

Velocity should be modified using addforce not directly.

basically this is the issue in a nutshell

1. adding a rigidbody to something means you want it to obey the laws of physics

2. velocity is the speed of something in each direction.

3. velocity when changed directly is an instantaneous change, so velocity = 500 or 0 means it instantly goes really fast or stops completely in 1 frame with no speeding/slowing just an instant change.

4. this change completely violates physics, if your going to do that modify the transform directly don’t use a physics component to do it.

so use