Please check [url=http://www.phy.ntnu.edu.tw/ntnujava/index.php?topic=4.0]2D Collision[/url] or  [url=http://www.phy.ntnu.edu.tw/ntnujava/index.php?topic=120]Collision 2D(EJS version)[/url]
for more information. You can find out the physics and the code from those two posts.