jQuery 实现小球撞击动画
以下是一个使用jQuery实现小球碰撞动画的简单示例:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ball Collision</title>
<style>
.ball {
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
position: absolute;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="ball" id="ball1"></div>
<div class="ball" id="ball2"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
JavaScript (jQuery):
$(document).ready(function() {
const BALL_RADIUS = 25;
const BALL1_INIT_POS = { x: 50, y: 50 };
const BALL2_INIT_POS = { x: 150, y: 50 };
const SPEED = 5;
function moveBall(ball, newPos) {
$(ball).css({
top: newPos.y + 'px',
left: newPos.x + 'px'
});
}
function checkCollision(ball1, ball2) {
const pos1 = $(ball1).position();
const pos2 = $(ball2).position();
const width1 = $(ball1).width();
const width2 = $(ball2).width();
const distX = Math.abs(pos1.left - pos2.left);
const distY = Math.abs(pos1.top - pos2.top);
const radiusTotal = BALL_RADIUS + BALL_RADIUS;
if (distX < (width1 + width2) / 2 && distY < (width1 + width2) / 2) {
const angle = Math.atan2(pos2.top - pos1.top, pos2.left - pos1.left);
const speed1 = { x: SPEED * Math.cos(angle), y: SPEED * Math.sin(angle) };
const speed2 = { x: -SPEED * Math.cos(angle), y: -SPEED * Math.sin(angle) };
moveBall(ball1, { x: pos1.left + speed1.x, y: pos1.top + speed1.y });
moveBall(ball2, { x: pos2.left + speed2.x, y: pos2.top + speed2.y });
}
}
function animate() {
moveBall('#ball1', { x: BALL1_INIT_POS.x += SPEED, y: BALL1_INIT_POS.y });
moveBall('#ball2', { x: BALL2_INIT_POS.x -= SPEED, y: BALL2_INIT_POS.y });
checkCollision('#ball1', '#ball2');
requestAnimationFrame(animate);
}
animate();
});
这段代码会创建两个小球,并且使它们在碰撞时进行碰撞动画。每次调用animate
函数时,小球的位置会更新,并且调用checkCollision
函数检查小球之间是否有碰撞。如果有碰撞,小球会反弹并继续移动。这个示例假设了没有其他物体与小球碰撞,并且没有考虑重力或其他物理效果。
评论已关闭