yandeu / arcade-physics

Use Arcade Physics without Phaser.
GNU Lesser General Public License v3.0
49 stars 3 forks source link

Ability to set origin of physics body #4

Open jamesward1 opened 1 year ago

jamesward1 commented 1 year ago

I don't believe currently there is an implemented way to set the origin of a body. I believe traditionally physics engines prefer to have the origin of the body be the center of the body, as it represents the standard center of mass.

I am able to make this change by hard coding values into Object2D of: this.displayOriginX = width / 2; this.displayOriginY = height / 2; this.originX = 0.5; this.originY = 0.5; But this doesn't seem like the best way, and the origin can't be altered in other scenarios later.

Is there any reason you opted to use 0, 0 as the origin? It looks like in Phaser the default is 0.5, 0.5. This also means you currently need to make weird conversion rules if you're using arcade-physics and a separate Phaser instance as a display (e.g. arcade-physics on the server, Phaser on the client).

yandeu commented 1 year ago

I haven't changed that. Maybe a sprite defaults to 0,5 and the physics takes that value. But I think the default physics body is 0,0.

yandeu commented 1 year ago

You are right. In Object2D.ts I set it to 0,0.


To put the body in the center, simply subtract the body.center:

const player = physics.add.body(0, 0, 40, 60)
player.position.subtract(player.center)
console.log(player.position) // Vector2 { x: -20, y: -30 }
jamesward1 commented 1 year ago

That will work, though it doesn't change the actual origin of the object. I modified the library, adding a "centered" parameter to the Object2D, Body, and StaticBody constructors, and pass it in through the factory method (default is false). If true, it sets the origin values to the ones I wrote out above. That seems to work. I'll see if anything breaks, but if not I think it's worth considering adding it to the library. Would be nice to give people this option.

jamesward1 commented 1 year ago

Actually doing as I described just moves the origin X and Y in the negative direction, much like what you described.

yandeu commented 1 year ago

The physics body itself does not have "origin". The origin comes from the Phaser Sprite. So the raw body has no understand of it.

In the future I will remove much more of the graphics stuff like "origin" and "displayOrigin". I believe all 2d physics engines use (0, 0) as top-left?

yandeu commented 1 year ago

But as described above. Each time you update the position of a body manually, just call player.position.subtract(player.center)

yandeu commented 1 year ago

In version 0.0.3 all the gameObjects have been removed and origin and displayOrigin is not available anymore. The "position" is now always the top left corner.