kripken / box2d.js

Port of Box2D to JavaScript using Emscripten
1.32k stars 196 forks source link

why is not show? #120

Closed a6965921 closed 2 years ago

a6965921 commented 2 years ago

` var restart; var canvas; var context; var Box2D; if (!Box2D) Box2D = (typeof Box2D !== 'undefined' ? Box2D : null) || Module; function startUp() { canvas = document.getElementById("canvas"); context = canvas.getContext('2d'); Box2D().then(function (r) { Box2D = r; Module = Box2D; var PTM=32; var s = window.location.search.substr(1); var NUM = s.length > 1 ? +s : 1;

    var NUMRANGE = [];
    while (NUMRANGE.length < NUM) NUMRANGE.push(NUMRANGE.length + 1);

    var bodies = [null]; // Indexes start from 1

    // Box2D-interfacing code

    var gravity = new Box2D.b2Vec2(0.0, -1.0);

    var world = new Box2D.b2World(gravity);
    var myDebugDraw = getCanvasDebugDraw();
    world.SetDebugDraw(myDebugDraw);

    var bd_ground = new Box2D.b2BodyDef();
    var ground = world.CreateBody(bd_ground);

    var shape0 = new Box2D.b2EdgeShape();
    shape0.Set(new Box2D.b2Vec2(0/PTM, 0/PTM), new Box2D.b2Vec2(20.0/PTM, 20.0/PTM));
    ground.CreateFixture(shape0, 0.0);

    var size = 1.0;
    var shape = new Box2D.b2PolygonShape();
    shape.SetAsBox(size, size);

    var ZERO = new Box2D.b2Vec2(0.0, 0.0);
    var temp = new Box2D.b2Vec2(0.0, 0.0);

    NUMRANGE.forEach(function (i) {
      var bd = new Box2D.b2BodyDef();
      bd.set_type(Box2D.b2_dynamicBody);
      bd.set_position(ZERO);
      var body = world.CreateBody(bd);
      body.CreateFixture(shape, 5.0);

      bodies.push(body);
    });
    setInterval(() => {
      world.Step(1 / 60, 2, 2);
      //black background
      context.fillStyle = 'rgb(0,0,0)';
      context.fillRect(0, 0, canvas.width, canvas.height);

      context.save();

      context.fillStyle = 'rgb(255,255,0)';
      world.DrawDebugData();

      context.restore();
      console.log(bodies[1].GetPosition().get_y());
    }, 60)

  })
}`