liabru / matter-js

a 2D rigid body physics engine for the web ▲● ■
MIT License
16.78k stars 1.96k forks source link

Fixed body angle #800

Closed robjinman closed 4 years ago

robjinman commented 4 years ago

I need a way to prevent a body (the player) from rotating. The method mentioned in https://github.com/liabru/matter-js/issues/622 has weird side effects - it causes the body to stick to walls and slide down them slowly.

robjinman commented 4 years ago

At the moment I've hacked it by making the player's body a circle and allowing it to freely rotate. Then, I ignore its angle when rendering the sprite.

morgan3d commented 4 years ago

This is called a "gyroscope" or "Cartesian" constraint--it allows translation but not rotation between bodies.

To do it properly, it needs to be handled within the constraint solver, which can currently only handle distance constraints. I hope that we'll see angular constraints built in to a future iteration for creating prismatic and Cartesian joints, which is the only big feature missing right now versus other 2D physics engines.

A quick and dirty hack is to lerp angle back towards the target angle and greatly dampen angular velocity and torque all within the constraint loop. If you don't want to modify matter.js, you can adjust them after the simulation update and then re-run a constraint distance iteration--that doesn't do as well of a job, but helps avoid some of the worst problems:

runMyConstraints();

Constraint.preSolveAll(allBodies);
for (let i = 0; i < physics.constraintIterations; ++i)
    Constraint.solveAll(allConstraints, physics.timing.timeScale);
Constraint.postSolveAll(allBodies);

runMyConstraints();

Using a circle for the character is a clever alternative, but you will find that the character builds up angular momentum sometimes and then appears to move for no reason to the player after a jump...and slopes can be a problem, due to rolling.

liabru commented 4 years ago

Interesting that you're having issues using the approach in #622, do you happen to have an example you could show?

How are you moving the player around? Depending on how you're doing it, it's possible that you need to also manually update velocities to get a correct response, see the body manipulation example and source.

@morgan3d

I hope that we'll see angular constraints built in

I have a (nearly) working implementation for them (but much like a lot of other features, tough get production ready).