# How to put enough force to a object so it bounces to the same height always

Im working with 2D physics.
I have a ball with a Circle Collider 2D(2D physics material - friction=0,bounciness=1) and a rigidbody2D attached to it(mass=1,drag=0,gravity=1)
The ground has a BoxCollider2D(no physics material no rigidbody)

I want the ball to bounce off the ground with Y velocity 7

So I set up a OnCollisionEnter2D function where I add more force to the ball or less force depending on how fast its going. the problem is that this method makes tresholds between velocities.

I need a code which gets the Y velocity of the ball and somehow calculates the ammount of force needed to add to the ball so the bounce off velocity will be 7
When I jump on a higher ground the velocity at the collision is less so it needs more force. When I jump from high ground to lower ground I need to add negative force to the ball so the bounce off velocity will be 7

this is my code

``````void OnCollisionEnter2D(Collision2D Col)
{
if(rigidbody2D.velocity.y<7.1)
{
if(rigidbody2D.velocity.y<5)
{
//Ball Y velocty less then 5 add more force
}
else
//Ball Y velocty less then 7.1 but more than 5 add less force
}
if(rigidbody2D.velocity.y>6.9)
{
//Ball Y velocty more then 6.9 add negative force
}
}
``````

Help plssss

If I understand your problem correctly then you could do this.

``````void OnCollisionEnter2D(Collision2D Col)
{

rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, 0); // set y velocity to zero
rigidbody2D.AddForce(new Vector2(0,1000)); // some constant force here
``````

}

rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, 0); // set y velocity to zero
rigidbody2D.AddForce(new Vector2(0,350)); // some constant force here

nice this fixed it

Thank you

@knunery
I used this script to make an object in my game keep the same velocity and it worked great, however when the object collides with a wall it continues to gain height up the wall, like a bouncing Spider-Man. What can be added to the script to prevent the object from interacting with the walls in such a way? So it only reacts to the floor? At the moment this is true with any other object with a collider attached to it.