schteppe / p2.js

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

Positioning planes at edges of canvas #255

Open lesliecdubs opened 8 years ago

lesliecdubs commented 8 years ago

Hey there - great library.

Is there any way to position planes exactly at the four edges of the canvas (left, bottom, right, top)? For reference, the canvas size is being set on load with JS due to a responsive layout.

schteppe commented 8 years ago

Hi, You need a way to convert a canvas coordinate to the corresponding physics/game world coordinate. For example, if your canvas is 400x300 pixels you want to position one of the planes on the edge center (400,150). You need to convert this to game space and place the plane there.

What game or rendering engine do you use? If you use plain HTML5 canvas, you can check the mouse joint example. In other engines there are often built in stuff for doing this.

lesliecdubs commented 8 years ago

Thanks for the quick response, @schteppe. I've actually been using the demo renderer, which I've altered a bit for our purposes.

Isn't the 'position' attribute using generic units (not pixels) to place planes at a specific location? If I could convert this to pixels it would be easy to do the math to position all the planes properly, but as it is I can't seem to figure out how to use the generic units to do this. Any insight?

schteppe commented 8 years ago

Ok! Looks like I used the built in stuff in Pixi.js to do convert to physics space: https://github.com/schteppe/p2.js/blob/85c93c9d77d3f23145238a541a07902d68615a8c/demos/js/WebGLRenderer.js#L178

Before I was using an own implementation (stagePositionToPhysics) to compute the physics position, but for now this method seem to do nothing.

The stage DisplayObject has the transform you need, from canvas to physics. So if you could use its transform to transform a point, you're done. http://pixijs.github.io/docs/PIXI.DisplayObject.html#toGlobal or http://pixijs.github.io/docs/PIXI.DisplayObject.html#toLocal on the stage object is what you're looking for.