传感器
演示
源代码
window.onload = function () { var w, h, canvas, ctx, world, circleBody, sensorBody; init(); requestAnimationFrame(animate); function init() { // 初始化画布 canvas = document.getElementById("renderCanvas"); w = canvas.width; h = canvas.height; ctx = canvas.getContext("2d"); ctx.fillStyle = 'green'; // 初始化物理引擎,并把重力加速度设置为0 world = new p2.World({ gravity: [0, 0] }); // 添加一个圆 circleShape = new p2.Circle(); circleBody = new p2.Body({ mass: 1 }); circleBody.damping = 0; circleBody.addShape(circleShape); world.addBody(circleBody); // 添加一个作为传感器的圆(它能检测到碰撞,但不进行碰撞反应的处理) sensorShape = new p2.Circle(); sensorShape.sensor = true; sensorBody = new p2.Body(); sensorBody.damping = 0; sensorBody.addShape(sensorShape); world.addBody(sensorBody); world.on("beginContact", function (event) { ctx.fillStyle = 'red'; }); world.on("endContact", function (event) { ctx.fillStyle = 'green'; }); } function drawCircle(ctx, body) { ctx.beginPath(); var radius = circleShape.radius; ctx.arc(body.position[0], body.position[1], 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); drawCircle(ctx, circleBody); drawCircle(ctx, sensorBody); 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] = 3 * Math.sin(world.time); // 进行物理效果的处理 world.step(timeStep, dt, maxSubSteps); // 绘制场景 render(time); } }
发布时间:2016/12/17 下午8:09:23 阅读次数:5028