添加一个球

效果

源代码

 window.onload = function () {
     var canvas, ctx, w, h, world, circleBody, planeBody;

     init();
     requestAnimationFrame(animate);                                

     function init() {

         // 初始化画布
         canvas = document.getElementById("renderCanvas");
         w = canvas.width;
         h = canvas.height;

         ctx = canvas.getContext("2d");
         ctx.lineWidth = 0.05;

         // 初始化引擎
         world = new p2.World();

         // 添加一个圆
         circleShape = new p2.Circle({ radius: 1 });
         circleBody = new p2.Body({ mass: 1, position: [0, 4] });
         circleBody.addShape(circleShape);
         world.addBody(circleBody);

         // 添加地面
         planeShape = new p2.Plane();
         planeBody = new p2.Body({position:[0,-3]});
         planeBody.addShape(planeShape);
         world.addBody(planeBody);
     }

     function drawCircle() {
         ctx.beginPath();
         var x = circleBody.interpolatedPosition[0],
             y = circleBody.interpolatedPosition[1],
             radius = circleShape.radius;
         ctx.arc(x, y, radius, 0, 2 * Math.PI);
         ctx.stroke();
     }

     function drawPlane() {
         var y = planeBody.interpolatedPosition[1];
         ctx.moveTo(-w, y);
         ctx.lineTo(w, y);
         ctx.stroke();
     }

     function render() {
         // 每次循环都需要清除canvas上的内容
         ctx.clearRect(0, 0, w, h);


         // canvas使用的坐标y轴向下,以像素为单位,而物理系统的y轴是向上的
         // 所以需要对画布进行坐标变换。
         ctx.save();
         ctx.translate(w / 2, h / 2);  // 将坐标原点设置到屏幕中央
         ctx.scale(50, -50);       // Zoom in and flip y axis

         // 绘制所有body对象
         drawCircle();
         drawPlane();

         // 重置画布的变换
         ctx.restore();
     }

     var lastTime, timeStep = 1 / 60, maxSubSteps = 5;

     // 绘制循环
     function animate(time) {
         requestAnimationFrame(animate);

         var dt = lastTime ? (time - lastTime) / 1000 : 0;
         dt = Math.min(1 / 10, dt);
         lastTime = time;

         // 进行物理模拟运算
         world.step(timeStep, dt, maxSubSteps);

         // 绘制场景
         render();
     }
 }

发布时间:2016/12/3 23:13:19  阅读次数:4034

2006 - 2024,推荐分辨率1024*768以上,推荐浏览器Chrome、Edge等现代浏览器,截止2021年12月5日的访问次数:1872万9823 站长邮箱

沪ICP备18037240号-1

沪公网安备 31011002002865号