so how can i assign a button to move red ball back and forth to avoid collision from blue ball. if collided then the blue ball should stop rotating. <div class="circle"> <div class="ball_blue"></div> <div class="ball_red"></div> </div> * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } @keyframes rot { from { transform: rotate(0deg) translate(-150px) rotate(0deg); } to { transform: rotate(360deg) translate(-150px) rotate(-360deg); } } .circle { border:1px solid grey; position: relative; width:300px; height:300px; margin:25px auto; border-radius:50%; } .ball_blue { width: 40px; height: 40px; position: absolute; top:50%; left:50%; margin-top: -20px; margin-left: -20px; background:blue; border-radius:50%; font-size: 100px; animation: rot 3s infinite linear; } .ball_red { width: 20px; height: 20px; position: absolute; background:red; border-radius:50%; /* INITIALLY CENTERED */ top:50%; left:50%; margin-top: -10px; margin-left: -10px; /* PUSH TO CIRCLE */ transform: translate(-150px); /* PUSH OUT OF CIRCLE */ margin-left: -20px; } Code (markup):
Depends on how far you want to go really... I have box2djs for you, which is pretty cool and can do what you want and much more, for download for free at http://seductiveapps.com/downloads/box2djs-0.2.0-jquery.zip It'll be fairly hard, beyond the math that I can remember, to make a routine in javascript that checks for just the collision of a box and a circle (at the edges of the circle i mean). I will let you in on the tip that if you want to do this in javascript, you should set the width: and height: of both ball and square in HTML, not in CSS. Or javascript can't "see" it in element.style.top/left..