The ball will generally bounce after hitting a wall, and the reflection angle = the incident angle;
In fact, it is very simple to use CSS3 to achieve this effect.
First, let’s break down the movement of the ball: horizontal movement and vertical movement.
When the ball moves to the lower right direction, if it hits the wall below, then due to the collision, the ball will receive a force perpendicular to the wall (that is, an upward force). In this case, the horizontal movement will not Only vertical movement is affected. Therefore, when the ball collides with the upper and lower walls, it only needs to change the direction of the up and down motion, and the left and right motion remains unchanged. By analogy, when the ball collides with the left and right walls, it only needs to change the direction of the horizontal motion, and the vertical direction does not need to be changed.
With this idea, you can start using css3 animation to realize the ball rebounding when it collides.
1.html:
1 <p id="box"> 2 <p id="ball-box"> 3 <p id="ball"></p> 4 </p> 5 </p>
2.css:
#box { width: 300px; height: 150px; border: 1px solid #7aa4c0; } #ball-box { width: 20px; height: 20px; border-radius: 10px; animation: bouncey linear 3s infinite; -webkit-animation: bouncey linear 3s infinite; } #ball { width: 20px; height: 20px; border-radius: 10px; background: -webkit-radial-gradient(circle, #ddecee, #0377db); background: -o-radial-gradient(circle, #ddecee, #0377db); background: -moz-radial-gradient(circle, #ddecee, #0377db); background: radial-gradient(circle, #ddecee, #0377db); animation: bouncex linear 5s infinite; -webkit-animation: bouncex linear 3s infinite; } @keyframes bouncey { 0%,100% { transform:translateY(0px); -webkit-transform:translateY(0px); } 50% { transform:translateY(130px); -webkit-transform:translateY(130px); } } @keyframes bouncex { 0%,100% { transform:translateX(0px); -webkit-transform:translateX(0px); } 50% { transform:translateX(280px); -webkit-transform:translateX(280px); } } css Code
The color of the ball uses the radial gradient in css3 to make The ball looks more three-dimensional.
The above is the detailed content of Implementation example of css animation ball hitting wall and rebounding effect. For more information, please follow other related articles on the PHP Chinese website!