ball going against wall - physics

Hello everybody.

I have started playing around with unity a few days ago. I'm trying to do a simple thing but i not successful. I'm trying to make a ball going against the inside walls of a box.

The problems is defining the movement of the ball after hitting the wall. I start by adding a force to de ball, but how i make it move realistic? Witch proprieties should i manipulate? I know that i have to considerate the mass of the 2 objects and the velocity, but i don't know how to do it in unity.

Thanks for your help ,

ngela

You can use the `OnCollisionEnter(Collision collisionInfo)` method for this purpose.

void OnCollisionEnter(Collision collisionInfo)
{
    rigidbody.AddForce(Vector3.Reflect(direction, 
                                      collisionInfo.contacts[0].normal) * mag,   
                       ForceMode.Impulse);
}

where direction and mag are the precached values of the rigidbody's current velocity direction and magnitude. The `Vector3.Reflect` simply gives you the reflected vector about the collision normal, which is the direction the bouncing ball should be heading in.

Also another way of simply using a bouncing ball in your scene, without any scripting needed, is by using the 'Bouncy' `Physics Material` for the ball collider. That should start it bouncing right away!

Hope it helps!

It really depends on what effect you are trying to achieve. On collision you have quite a bit of stuff available to you.

The Collision class, which is what is holding all of the info you need to know about the collision event that just took place:

(this is directly from Unity docs)

Variables

relativeVelocity - The relative linear velocity of the two colling objects (Read Only).

rigidbody - The Rigidbody we hit (Read Only). This is null if the object we hit is a collider with no rigidbody attached.

collider - The Collider we hit (Read Only).

transform - The Transform of the object we hit (Read Only).

gameObject - /gameObject/ is the object we are colliding with. (Read Only).

contacts - The contact points generated by the physics engine

What you can also see at this point, by accessing this.rigidbody (assumming this script is applied to the ball), is the "velocity" property in Vector3 format. Velocity would be something like this x:0,y:1,z:0 meaning each physics step it is moving 1 unit up on the Y-axis and none in any direction. This would be a ball ascending straight up.

With all this information available and a basic knowledge of physics; you would just use rigidbody.AddForce(vec3,ForceMode.Force) (or any other type of force mode) to change the trajectory of the ball to make it behave as desired.

Hope this helps,

==

Hi okstok and equalsequals !

Thanks for your help. I will post the resulting as soon as I can.