添加一个矩形

源代码

 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();

         // 添加一个矩形
         boxShape = new p2.Box({
           width: 2,
           height: 1
         });
         boxBody = new p2.Body({
           mass: 1,
           position: [0,3],
           angularVelocity: 1
         });
         boxBody.addShape(boxShape);
         world.addBody(boxBody);

         // 添加地面
         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);        // 将画布扩大50倍并使y轴反向

         // 绘制所有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/4 22:43:14  阅读次数:4035

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

沪ICP备18037240号-1

沪公网安备 31011002002865号