利用jquery和高中学物理写的物体自由落体。ps:底边碰撞部分和最后物体禁止部分都写得不太好。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>drop</title>
<script type="text/javascript" src="jquery-1.6.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".drop").click(function(){
var box2=new freedrop(".drop");
box2.drop(1000/*初始速度,单位(m/ms)*/,600/*高度:单位(px)*/,0.9/*碰撞速度变化范围(理论上0至1,但大于也行)*/);
});
})
function freedrop(idORclass){ //自由落体构造函数freedrop(id或class)
this.velocity=0;
this.gravity=1000; // 重力加速度单位:m/(ms^2)(地球g=10000m/s^2)ps:范围在1000左右效果比较好
this.longTopx=0.0003; // 长度和像素的近似转换单位:px/m
this.stopNow=null;
this.bottom=0; //物体距离底边的距离
this.tAnimate=1; //调用jquery的animate()函数的时间参数
this.hit=1; //碰撞后速度的变化范围0~1
this.drop=function(velocity,bottom,hit){ //函数drop(初始速度,高度)
this.velocity=velocity;
this.bottom=bottom;
this.hit=hit;
stopNow=setInterval(this.move(this,this.velocity,this.bottom,this.gravity,this.tAnimate,this.longTopx,this.hit),this.tAnimate);
}
this.move=function(obj,velocity,bottom,gravity,tAnimate,longTopx,hit){ //函数move()
return function(){
var positionChange=(velocity*tAnimate+(1/2)*gravity*tAnimate*tAnimate)*longTopx; // ds=v0*t+(1/2)g(t^2)
velocity=velocity+gravity*tAnimate; //v=v0+gt
obj.velocity=velocity;
bottom=bottom-positionChange;
obj.bottom=bottom;
if(obj.bottom<=5){
velocity=(0-velocity)*hit; //碰撞后速度的变化
obj.velocity=velocity;
if (Math.abs(obj.velocity)<=1){
clearInterval(stopNow);
return;
}
}
$(idORclass).animate({bottom:bottom+"px"},tAnimate);
}
}
}
</script>
<style type="text/css">
.drop{
width:100px;
height:100px;
background-color:#00FF66;
bottom:600px;
position:absolute;
}
</style>
</head>
<body>
<div class="drop">clickme</div>
</body>
</html>