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

/*代码如下*/

<!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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值