传感器2
演示
源代码
window.onload = function () { var w, h, canvas, ctx, world, circleBody, sensorSize = 1.4, inactiveColor = 'green'; var sensors = []; init(); requestAnimationFrame(animate); function init() { // 初始化画布 canvas = document.getElementById("renderCanvas"); w = canvas.width; h = canvas.height; ctx = canvas.getContext("2d"); ctx.fillStyle = 'green'; // 初始化物理引擎 world = new p2.World({ gravity: [0, 0] }); // 添加一个圆 circleShape = new p2.Circle({ radius: 0.3 }); circleBody = new p2.Body({ mass: 1 }); circleBody.damping = 0; circleBody.addShape(circleShape); circleBody.color = 'red'; world.addBody(circleBody); // 添加四个正方形传感器 for (var i = 0; i < 4; i++) { sensorShape = new p2.Box({ width: sensorSize, height: sensorSize }); sensorShape.sensor = true; var pos = [sensorSize / 2, sensorSize / 2]; if (i == 1) { pos[0] *= -1; } else if (i == 2) { pos[1] *= -1; } else if (i == 3) { pos[0] *= -1; pos[1] *= -1; } sensorBody = new p2.Body({ position: pos }); sensorBody.damping = 0; sensorBody.addShape(sensorShape); sensorBody.active = false; world.addBody(sensorBody); sensors.push(sensorBody); } world.on("beginContact", function (event) { for (var i = 0; i < sensors.length; i++) { var s = sensors[i]; if (event.bodyA == s || event.bodyB == s) { s.active = true; } } }); world.on("endContact", function (event) { for (var i = 0; i < sensors.length; i++) { var s = sensors[i]; if (event.bodyA == s || event.bodyB == s) { s.active = false; } } }); } function drawObjects(ctx) { // 绘制传感器 for (var i = 0; i < sensors.length; i++) { ctx.fillStyle = sensors[i].active ? 'red' : 'green'; ctx.fillRect( sensors[i].position[0] - sensorSize / 2, sensors[i].position[1] - sensorSize / 2, sensorSize, sensorSize ); } // 绘制圆形 ctx.fillStyle = 'blue'; ctx.beginPath(); ctx.arc(circleBody.position[0], circleBody.position[1], circleShape.radius, 0, 2 * Math.PI); ctx.fill(); } function render() { ctx.clearRect(0, 0, w, h); ctx.save(); ctx.translate(w / 2, h / 2); ctx.scale(50, -50); drawObjects(ctx); 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; circleBody.position[0] = 1 * Math.cos(world.time); circleBody.position[1] = 1 * Math.sin(world.time); // 进行物理模拟 world.step(timeStep, dt, maxSubSteps); // 绘制场景 render(time); } }
发布时间:2016/12/18 下午3:39:57 阅读次数:4690