Jump to content

Anchoring a p2 body with arbitrary shape on a tile


substandardgaussian
 Share

Recommended Posts

I wanted to give P2 physics a little more support for non-square tiles, so I'm working on a utility that builds bodies for tiles. For my purposes, a tile can be anchored either to the top or bottom (has a full-length edge that is the same length as the edge of the tile), but can be sliced anywhere else with an arbitrary slope. Actually making the body is easy... but trying to place the body in the right spot is proving to be difficult.

 

When you make p2 bodies, everything is based around their center of mass. This is entirely unhelpful, because I need a particular vertex of the body to be glued to a particular vertex of the tile image, and with arbitrary slices/angles, the polygon I end up with can have completely arbitrary offsets from where it's supposed to be. I don't want the center to be in a known position, I want a vertex to be in a known position. I've tried doing a translation by the centroid of the polygon, but it doesn't line up consistently.

 

Does anyone know how I can tackle this problem? All operations on p2 bodies seem to be relative to the center of mass.

Link to comment
Share on other sites

Figured it out! It is... not fun.

var len = [this.world.pxmi(tile.width), this.world.pxmi(tile.height)];//find the anchor axis                var ref = null;                for (var i = 0; i < this.data.shapes[0].vertices.length; i++) {                        var axis = this.data.shapes[0].axes[i];                        if (axis[0] == 0 && axis[1] == -1) {    //normal axis to our line, guaranteed by the constraints on the tile body                               ref = i;                                break;                        }                }if (ref != null) {      this.data.shapeOffsets[0][0] += len[0] - this.data.shapes[0].vertices[ref][0];    this.data.shapeOffsets[0][1] += len[1] - this.data.shapes[0].vertices[ref][1];                                 }

This only works given that we're looking to lock the bottom-right vertex for a body that contains only one horizontal line (or we might find the right side of the other horizontal line first): regular rectangles are handled separately. There is a different case for each different "type" of tile constructed.

 

In this case, moving the body's position has the same effect as moving the shape's offset. I think this could be generalized to create a P2.Body.anchor property that moves the point around which all body operations are performed. Moving the vertices explicitly instead of just changing the offsets causes P2 to freak out pretty hilariously with its collision detection and responses.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...