schteppe / p2.js

JavaScript 2D physics library
Other
2.64k stars 329 forks source link

Сreate static body with sizes #167

Closed lgick closed 9 years ago

lgick commented 9 years ago

I create tiles game.

My code:

var map = [
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];
var step = 32;
var x, y, lenX, lenY, tile, body;

for (y = 0, lenY = map.length; y < lenY; y += 1) {
  for (x = 0, lenX = map[y].length; x < lenX; x += 1) {
    tile = map[y][x];

    if (tile === 1) {
      body = new p2.Body({
        position: [x * step, y * step],
        type: p2.Body.STATIC
      });

      body.addShape(new p2.Rectangle(step, step));
      world.addBody(body);      
  }
}

Result:

2015-06-21 2 13 27

Red lines - real size my tiles. But my tiles are created with width and height. Why is this happening?

Help! Thank you!

schteppe commented 9 years ago

Hi,

Your tiles have their position in the upper left corner and the bodies have their position in the center. So you need to add size/2 to x and y to the body position.

By the way, positive Y is up in p2, and probably down in your game... How do you solve that?

The rectangle size should be correct though... Not sure what happened there. Maybe you could copy one of the demos in the p2 repo (see demos/), paste in your code and see what's up.

While I think this solution of yours is a good start, I also think that you should merge your rectangle bodies to get better physics performance. The scene you have in this example can be made with 4 long rectangle bodies, which should be much more performant. This merge part should be possible to make automatic, but I don't have code for that, sorry.

schteppe commented 9 years ago

This is how the scene looks in a p2 Demo. Don't think there's any problem with the size, just the offset.

skarmavbild 2015-06-21 kl 19 00 02

lgick commented 9 years ago

With offset (to add size/2) - it works! Thank you! You are right, positive Y goes down, but at the moment it works normal with p2.

Yes, I will combine tiles into blocks! Thanks!

schteppe commented 9 years ago

Nice!