碰撞检测:圆的碰撞运动,关键在于碰撞后速度的分解问题

来源:互联网 发布:网络摄像头一天多少g 编辑:程序博客网 时间:2024/04/29 22:13

/*代码如下*/

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圆的碰撞</title>
<style>
#div1 {width:200px;height:200px;background: red;border-radius: 50%;position:absolute;left:600px;top:100px;}
#div2 {width:150px;height: 150px;background: blue;border-radius: 50%;position:absolute;left:100px;top:250px;}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
<script>
oDiv1=document.getElementById("div1");
oDiv2=document.getElementById("div2");
var speed=10; //div2的运行速度v
var v_v1=0;
var v_v2=0;
var v1_vx=0;
var v1_vy=0;
var v2_vx=0;
var v2_vx=0;
var v3_vx=0;  //v1的反向速度,也即v2的速度
var v3_vy=0;
var x=0;
var y=0;

setInterval(function(){
var dis_l=Math.abs((oDiv1.offsetLeft+100)-(oDiv2.offsetLeft+75));
var dis_t=Math.abs((oDiv1.offsetTop+100)-(oDiv2.offsetTop+75));
var deg=Math.atan(dis_t/dis_l);

oDiv2.style.left=oDiv2.offsetLeft+speed+"px";

if(Math.sqrt((Math.pow(dis_l,2)+Math.pow(dis_t,2)))<=175){
v_v1=speed*Math.cos(deg);
v_v2=speed*Math.sin(deg);

//div1的x,y的速度
v1_vx=Math.cos(deg)*(v_v1);
v1_vy=Math.sin(deg)*(-v_v1); //往上是负的

//div2的x,y的速度
v2_vx=Math.sin(deg)*v_v2;
v2_vy=Math.cos(deg)*v_v2;

v3_vx=Math.cos(deg)*(-v_v1); //往左是负的
v3_vy=Math.sin(deg)*(v_v1);

x=v2_vx+v3_vx; //div2水平方向的合速度
y=v2_vy+v3_vy;

}
oDiv1.style.left=oDiv1.offsetLeft+v1_vx+"px";
oDiv1.style.top=oDiv1.offsetTop+v1_vy+"px";

oDiv2.style.left=oDiv2.offsetLeft+x+"px";
oDiv2.style.top=oDiv2.offsetTop+y+"px";

},30);

</script>
</html>


原创粉丝点击