传感器

演示

源代码

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

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

沪 ICP 备 18037240 号-1

沪公网安备 31011002002865 号