Bouncing Ball Effect

I want to add bouncing ball effect to my sphere object. I have added two empty game object with box collider which acts as a boundry or wall. But i am not finding the way to change the direction such that it gives effect like bouncing when the ball hits to those boundry. So what do i need to write on collision detection . I have tried code from this http://answers.unity3d.com/questions/28037/question-pongball-to-change-direction.html

But it goes out of my plane.

Script which i have written to shoot my ball is here:

function Update ()
{
	  var hit  : RaycastHit ;
      var ray : Ray  = Camera .main .ScreenPointToRay (Input .mousePosition );
      if(Physics.Raycast (ray, hit))
      {     
	     var tempx = hit.transform.position.x;
	     var tempy  = hit.transform.position.y;
	     velocity = Vector3(tempx,tempy,0);
      }
      
      if(velocity != null){
        // set the max move amount
        var moveAmount : float = 5f * Time.deltaTime;
        // translate the move amount
        transform.Translate(velocity * moveAmount);
     }    
}

Please help me to solve my problem. Thanks for your help and support in advanceā€¦

Here is an answer that is totally different to the question, using physics and rigidbodies.

  • I tested this by making a new scene, then created a sealed room with 6 box colliders.
  • then created a sphere. I renamed this Bubble
  • To the Bubble sphere object, I attached a rigidbody component, and disabled gravity.
  • Then I imported the Unity Physics Materials (Standard Assets. Assets > Import Package > Physic Materials), then added the bouncy material to the sphere collider of the Bubble object.
  • Then I attached the following script.
  • Then I duplicated the Bubble object 20 times and scattered them around the room.

here is the script :

#pragma strict
@script RequireComponent( Rigidbody )

var myTransform : Transform;
var myRigidbody : Rigidbody;

var forceToAdd : float = 2.0;

function Start() 
{
	myTransform = transform;
	myRigidbody = rigidbody;
	
	myRigidbody.velocity = Random.insideUnitSphere * forceToAdd;
}

function Update() 
{
	
}

function OnCollisionEnter( other : Collision ) 
{
	if ( other.collider.gameObject.name == "Bubble" )
	{
		myRigidbody.velocity = Vector3.zero;
	}
	
	// uncomment this part to add additional bounce 
	/*
	else
	{
		var localHitPoint : Vector3 = other.contacts[0].point - myTransform.position;
		var newHitForce : Vector3 = ( myTransform.position - other.contacts[0].point ).normalized * forceToAdd;
		
		//Debug.Log( "World hit point = " + other.contacts[0].point + " : Local hit point = " + localHitPoint + " : new Hit Force = " + newHitForce );
		
		myRigidbody.AddForceAtPosition( newHitForce, localHitPoint, ForceMode.Impulse );
	}
	*/
}

on the box collider, click on Material then click Bouncy