2.224 不定义 position="absolute" 的话,left 和 top 是无效的 - 方块不会动的说
2.3 可以移动的方块
2.31 物理模型和面向对象
运行代码框<div style="width:140px; height:140px; background-color:pink; cursor:pointer;" id="divBlock" ></div> <script> f=0.95; // 运动阻尼 k=0.85; // 碰撞弹性系数 g=1; // 重力加速度 window.onload=init; function init(){ var obj; obj=document.getElementById("divBlock"); obj.speedX=parseInt(Math.random()*5); obj.speedY=parseInt(Math.random()*5); obj.move=function(){ // 这里俺暂时不写,呵呵 } } </script>
2.311这个模型很简单:物体的属性:速度(包含 x 分量和 y 分量,这里设置为一个0-5的随机数)物体的方法:运动环境属性:运动阻尼 f, 和窗口边缘碰撞弹性系数 k, 重力加速度 g
2.312 注重 obj.move 那个方法(函数)的写法
2.32 让方块动起来
运行代码框<div style="width:140px; height:140px; background-color:pink; cursor:pointer; position:absolute;" id="divBlock" ></div> <script> f=0.005; // 运动阻尼 k=0.7; // 碰撞弹性系数 g=1; // 重力加速度 var obj; window.onload=init; function init(){ obj=document.getElementById("divBlock"); obj.speedX=140; obj.speedY=400; obj.move=function(){ var x, y, mx, my; x=this.offsetLeft; y=this.offsetTop; mx=document.body.clientWidth-this.offsetWidth; // 计算答应运动的最大范围 my=document.body.clientHeight-this.offsetHeight; this.speedY =g; // 计算重力加速度影响的y方向速度 this.speedX-=f*this.speedX*this.speedX*(this.speedX>0?1:-1); // 计算阻尼后的速度 this.speedY-=f*this.speedY*this.speedY*(this.speedY>0?1:-1); // 阻尼大小和速度平方成正比 if(Math.abs(this.speedX)>mx||Math.abs(this.speedY)>my){ this.speedX=this.speedX%mx; this.speedY=this.speedY%my; } x =this.speedX; y =this.speedY; // 计算坐标 if(x<0){ x=-x; this.speedX=Math.abs(this.speedX)*k; } // 计算边界碰撞 if(y<0){ y=-y; this.speedY=Math.abs(this.speedY)*k; } if(x>mx){ x=mx*2-x; this.speedX=-Math.abs(this.speedX)*k; } if(y>my){ y=my*2-y; this.speedY=-Math.abs(this.speedY)*k; } if(Math.abs(this.speedX)<1)this.speedX=0; // 消除数据下溢 if(Math.abs(my-y)<4&&Math.abs(this.speedY)<4){ y=my; this.speedY=0; } // 消除临界状态的抖动 this.style.left=parseInt(x) "px"; // 实现移动 this.style.top=parseInt(y) "px"; } setInterval("obj.move();",10); } </script>