schteppe / p2.js

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

Scaling/rotating a body from a polygon? #220

Closed AndrewRayCode closed 5 years ago

AndrewRayCode commented 8 years ago

I have a series of points that define the outline of a wall. I'm using body.fromPolygon(points).

I'd like to make multiple copies of this wall that are scaled / rotated. Do I have any options other than re-creating the polygon points at each new scale/rotation? With box shaped walls it's easy because I can give the shape a width and height.

schteppe commented 8 years ago

The latest master version makes a copy of the path array, so you can re-use the array of points. For different rotations, you can simply set the rotation on the Body or the Shape, and re-use the same path array. For different scales, I'm afraid you'll have to make a new path array each shape.

Under the hood, all the data is copied and cannot be reused in between bodies. I guess this is a good place for improvement - maybe implementing something like the box2d fixtures could help. With a fixture to attach a shape to a body, the shape data could probably be re-used easily. However, I'm not sure if it would solve the scale problem.

jtenner commented 8 years ago

@DelvarWorld would a simple module that scales/rotates/translates points be helpful? I've been meaning to write one.

AndrewRayCode commented 8 years ago

@jtenner the internal vec2 library for p2.js already has all of those method. I was just hoping I could be even lazier out of the box :)

jtenner commented 8 years ago

Yeah but you have to map each coordinate to each transform in order instead of making a single transform matrix and transforming a set of points. That's a lot more cpu work than needed.

I know vec2 exists, but I'm talking about making something fully featured.

MaxPleaner commented 7 years ago

I am not sure how to write any scale functions in terms of changing the points list. But scale / anchor changes are useful and the hitboxes (polygons) are not updating as a result. If someone could show an example, I'd appreciate it.

MaxPleaner commented 7 years ago

Gif 1 is using the 1:1 scale sprite and the collision is correct at the bottom the screen. Gif 2 using 0.5 scale and the hitbox is no longer correct:

bug1

bug2

This is coffeescript to set up the sprite:

# in create
@ball = @add_p2_sprite @ball_start_x, @ball_start_y, 'ball'
@ball.body.clearShapes()
@ball.body.loadPolygon 'ball_physics', 'ball'

I get that I should probably use a p2 Circle instead of physics file for the ball, but it's still an issue in other situations.