matter-js icon indicating copy to clipboard operation
matter-js copied to clipboard

Prevent object passing through walls / tunneling (implement CCD)

Open liabru opened this issue 10 years ago • 85 comments


If you need fast moving or thin bodies a simple and robust solution is to sub-step using multiple updates per frame:

See the example here: https://github.com/liabru/matter-js/issues/5#issuecomment-1050738814

As well as sub-steps also consider:

  • make thin bodies thicker (but can render them thinner similar to this example)
  • apply a max speed limit to bodies (e.g. similar to this example)
  • avoid large timesteps (<= 16.666ms is recommended)
  • ray cast along body velocity and clamp velocity to e.g. 50%

Currently there is no continuous collision detection (CCD), so fast moving objects pass through other objects.

A description of the problem: http://www.stencyl.com/help/view/continuous-collision-detection

Solution is to implement a CCD algorithm.

One I'm currently considering is speculative contacts, see here and here.

"we compute the closest distance d between the two objects; the idea is that we want to remove exactly the right amount of velocity from A such that it will be exactly in touching contact with B on the next frame"

I've already implemented the code that extends the AABB based on object velocity.

The next part is to find the closest distance between two objects and remove the required velocity.

liabru avatar Feb 27 '14 21:02 liabru

I just added a poor man's solution to the tunneling problem. It detects if a body is outside the world bounds and then reverses the velocity and translates the body back. I tried via an event. Here is the code. Please have a look. Events.on(_engine, 'afterTick afterRender', function (event) { // avoid tunneling for (var i = 0; i < _world.bodies.length; i++) { var bodyA = _world.bodies[i]; if (bodyA.isStatic || bodyA.isSleeping) { continue; } var outside = false; var adjustX = 0; var adjustY = 0; var epsilon = 0.01; if (bodyA.bounds.min.y + epsilon >= _world.bounds.max.y) { // bottom adjustY = Math.abs(bodyA.bounds.max.y - _world.bounds.max.y); Body.translate(bodyA, { x: 0, y: -adjustY }); bodyA.velocity.y = -1.0; outside = true; } if (bodyA.bounds.max.x - epsilon<= _world.bounds.min.x) { // left bodyA.velocity.x = 1.0; adjustX = Math.abs(bodyA.bounds.min.x - _world.bounds.min.x); Body.translate(bodyA, { x: adjustX, y: 0 }); outside = true; } if (bodyA.bounds.max.y - epsilon <= _world.bounds.min.y) { // Top adjustY = Math.abs(bodyA.bounds.min.y - _world.bounds.min.y); Body.translate(bodyA, { x: 0, y: adjustY // since body.bounds.min.y is negative }); bodyA.velocity.y = 1.0; outside = true; } if (bodyA.bounds.min.x + epsilon > _world.bounds.max.x) { // right bodyA.velocity.x = -1.0;adjustX = Math.abs(bodyA.bounds.max.x - _world.bounds.max.x); Body.translate(bodyA, { x: -adjustX, y: 0 }); outside = true; } if (outside) { Bounds.update(bodyA.bounds, bodyA.vertices, bodyA.velocity); } } });

abataille avatar Mar 14 '14 11:03 abataille

Thanks for sharing, but does this work?

I ask because body.velocity is technically read only - the engine uses position Verlet meaning velocity is implicit to changes in position (see here)!

So what you need to do instead is simply set the body position to be inside the world, the engine will handle the velocity change for you.

Either way, as you say this is indeed a poor mans solution, as it's only a solution to going outside of the world bounds.

BTW note the event name is not 'afterTick afterRender', those are two separate events (that happen to relate to the same point in the step). You only need to use one here (e.g. it's like jQuery's events), otherwise this will run twice per step.

What we really need implementing is speculative contacts. I'll get round to it at some point hopefully!

liabru avatar Mar 14 '14 12:03 liabru

You are right. velocity change is not necessary. Just the translation does it. I know, it does not work for inside objects, but at least it leaves the bodies at the table.

abataille avatar Mar 14 '14 12:03 abataille

+1

shakiba avatar May 11 '14 05:05 shakiba

Still experiencing this issue, I guess it's still unsolved?

Danetag avatar Nov 11 '14 18:11 Danetag

It's a pretty big feature to implement really, I've played around with some ideas for this but I've not yet got much working. It's a tricky one.

I'm considering implementing a simple version for now (ray casting) that should prevent some of the more obvious tunneling cases.

liabru avatar Nov 11 '14 23:11 liabru

Ok I totally understand, thank you so much for all your hard work :)

Danetag avatar Nov 12 '14 00:11 Danetag

Note that increasing engine.timing.timeScale can cause this issue as well.

anjiro avatar Feb 16 '15 18:02 anjiro

Still having this issue using latest master as of e698b6b5be5d8e4d5ddfb6fa06436916f5ef4772. I have somewhat mitigated it by halving the engine.timing.timeScale value. Not sure of the repercussions of this, but works for my simple use case.

isaac-jordan avatar Nov 27 '15 14:11 isaac-jordan

+1

homerjam avatar Jan 15 '16 15:01 homerjam

@liabru for https://cubeslam.com I ported a few SAT implementations to javascript but finally fell for this brilliant SAT implementation and converted it to be a part of this library.

It's very similar to your implementation but will also project ahead based on the polygons relative velocity to see if it will intersect and then returns a minimum translation vector which may be applied to keep two polygons from colliding if desired.

I found it to be quite stable and fast even in the pace of cube slam. Unfortunately google code just shut down so the implementation code for it is not viewable online anymore. But you can download it and have a look at the narrowphase implementation in lib/sim/physics.js#L74.

slaskis avatar Jan 28 '16 09:01 slaskis

@slaskis I remember playing with cubeslam, awesome project!

Thanks for the info. I actually played with using SAT for continuous collisions but I couldn't get it working at the time, so I'll take a look at your implementation for some pointers.

liabru avatar Jan 28 '16 18:01 liabru

@liabru thanks! I hope it can help you get this sweet library even better

slaskis avatar Jan 28 '16 18:01 slaskis

+1 Seeing lots of tunneling with bodies passing through svg generated bodies.

dcrockwell avatar Feb 07 '16 07:02 dcrockwell

Is there any workaround for this issue? The proposal from @abataille doesn't work for me.

ser10us avatar Mar 28 '16 11:03 ser10us

Not yet, I have a work in progress implementation. Depending on your needs, you could try doing some ray casts between updates (e.g. between centroids of bodies moving over a certain speed), if there's an intersection then move the body back. This won't be perfect but might help for some cases.

liabru avatar Mar 28 '16 18:03 liabru

@liabru would you mind sharing your in progress implementation as a PR or branch? I'm curious what it looks like and maybe we can help out?

slaskis avatar May 11 '16 08:05 slaskis

Will this also allow collision with simple lines? To be more specific imagine a force field, which limits you to not pass from both sides but has no thickness. Which comes to the second idea of force fields coliding only in one direction, so you might move into the forcefield, but not leave it again. Imagine it as a simple polygon which has only a one-sided face, you walk through it as you cannot see it. If you try to move back you see a wall there. Used that feature to build some nasty tricky puzzles in prey a while ago, where the back-side was a portal placed inside a door. Which results in a door bringing you from a to b, but the same door back brings you from b to c :D

IceReaper avatar May 14 '16 08:05 IceReaper

@slaskis it is in a very unstable state, I was trying a different approach than using SAT. But it looks like it's not going to be viable, so I'm going to try implement it again in the same way you did. Looking at your code, the key part seems to be these lines right?

liabru avatar May 14 '16 09:05 liabru

@IceReaper if the implementation was perfect, then yes you could do a super thin body and it should never let anything through. I'm not sure if a practical implementation will be that accurate though, but hopefully.

Either way, for the kind of game mechanics you are talking about, it is better for you to implement that logic directly as it's not really in the scope of a physics engine but rather a game engine. Though once plugins are implemented (#213) you could use them to integrate this.

liabru avatar May 14 '16 09:05 liabru

@liabru yep, that's the part that uses the velocity to find the possible intersection.

And then the following lines may be useful for knowing how much to "push" the object back to the right side of the polygon.

slaskis avatar May 14 '16 10:05 slaskis

I've made some progress on this based on the technique @slaskis mentioned, so far it seems pretty viable. I'll commit it to a branch as soon as it is working well enough.

liabru avatar Jun 02 '16 10:06 liabru

I've just pushed my implementation to the ccd branch. If anybody wants to try it then use the build on that branch.

To use continuous collisions then set the body.continuous property to one of these values:

  • 0 - disabled (default)
  • 1 - dynamic (recommended)
  • 2 - always

Where the 'dynamic' setting enables continuous collisions only when required based on velocity. This provides better performance than 'always' at the cost of slightly softer collisions. In a collision if either or both bodies have continuous collisions enabled then the check will be made.

See the included Example.continuousCollisions in the demo.

Let me know how you get on if you try it!

liabru avatar Jun 05 '16 23:06 liabru

@liabru that looks great, much more readable than my mess. I'll see if I get a chance to try it out this week

slaskis avatar Jun 06 '16 10:06 slaskis

Can we get some performance metrics between the different modes?

dcrockwell avatar Jun 06 '16 20:06 dcrockwell

I could look into it, but I can say already that even the 'always' mode is very performant. Though it changes the behaviour of a lot of the demos because the collisions are detected earlier, which causes some things to collapse (the 'dynamic' mode is fine though because it only applies to high speed collisions).

liabru avatar Jun 06 '16 22:06 liabru

Unfortunately I'm still experiencing a similar issue. Is there any way to cap the velocity of a body to a hard limit? This might be a quick fix for me.

Edit: it just so happens the bodies that they're going through are on the boundary of the canvas, also. Debugging someone else's code right now, not sure if there is another issue at play but figure the velocity cap would be worth trying.

joshkpeterson avatar Jul 12 '16 21:07 joshkpeterson

Yeah you could cap the body velocity in the engine update event quite easily. Either way, the CCD code will get merged soon after I finish work on #213 so you won't need to after that.

liabru avatar Jul 13 '16 09:07 liabru

I tried using the new build with the CCD code and setting continuous to 2 on all the bodies, but they're still going through walls / the boundary. The bodies are circles by the way, and the smaller they are the easier it is to get them to escape.

I also tried on engine update checking to see if the velocity is greater than (+/-)20, and if so, capping to (+/-)20, but it's still easy to get them out. Basically if you just click and drag them to the boundary and hold them there, they start spinning and bouncing like crazy and fly out.

There's probably another issue with my build that is causing this issue, but just wanted to let you know. I'd like to get you a case, but right now this is part of a larger framer.js project that I can't share. If I have time to break it out I will.

joshkpeterson avatar Jul 13 '16 22:07 joshkpeterson

I tried using the new build with the CCD code and setting continuous to 2 on all the bodies, but they're still going through walls / the boundary.

What are you doing to cause them to escape? Setting velocity, adding force or using the mouse or constraints? Does the CCD demo work for you? How are the walls constructed?

Basically if you just click and drag them to the boundary and hold them there, they start spinning and bouncing like crazy and fly out.

There are some cases where CCD checks won't always be applied (e.g. things that 'teleport' or force positions, like constraints). Note that also there are no boundary checks, the space is infinite. If this is the case then it may be tricky to fix.

liabru avatar Jul 14 '16 09:07 liabru

The walls are Matter.Bodies.rectangle(). I'm using a MouseConstraint to move the circles.

Edit: I just built the CCD demo, and I'm able to just drag the squares through the center rectangle at will not through the outer rectangles. I figured out this is because the squares are both 1) really big and 2) overlapping at the corners. I implemented in my own application, and using the new CCD stuff seems to help (circle's don't exit as often) but it doesn't take it all the way. The walls still have to be really big and overlapping.

So from where I stand the CCD fix isn't really working yet. If someone else want to build the demos and try out the CCD one that would be great.

Thanks again for your help.

joshkpeterson avatar Jul 14 '16 15:07 joshkpeterson

I build the demos and I am also able to drag the little rectangles through the small bar in the middle. I also managed to get them through by making them really, really fast/applying a lot of force.

I am using this branch for my game at the moment, and regardless of it not working at very, very, very high speeds it is making things much more stable, so this implementation is already a win for me. :)

This is how the demo looks at the start for me. This is how much I can "drag" it until it gets through.

BastianGanze avatar Jul 20 '16 00:07 BastianGanze

Either way, the CCD code will get merged soon after I finish work on #213 so you won't need to after that.

Is it time? :)

staff0rd avatar Nov 08 '16 07:11 staff0rd

Any update on the ccd merge? I see it has a release-candidate label, that sounds promising!

wmike1987 avatar Feb 03 '17 15:02 wmike1987

Any updates on this issue?

Buri avatar Jul 02 '17 12:07 Buri

Unfortunately there were some issues with this initial approach after a bunch of testing. I've got a new approach I'm working on though which should be simpler and more performant too.

liabru avatar Jul 03 '17 10:07 liabru

@liabru can the new approach do with help? Any specific things that'd push it along?

maltenuhn avatar Aug 09 '17 09:08 maltenuhn

I have an idea. The object falls through the wall because the hitbox is too small. If the hitbox was bigger it would fix it. The size should be the size to the object + the velocity in that direction. If the object fall down the hitbox should be the size of the object + the y-velocity downwards.

theodorklauritzen avatar Aug 15 '17 18:08 theodorklauritzen

@liabru Any update on this? It looks like you abandoned the CCD branch and maybe are implementing your new approach in a different branch? Perhaps I can help code it up. I'm trying to make a game for mobile and this is the most performant 2D physics JS library I've found so far. Just need to get this bit fixed.

spiderworm avatar Dec 05 '17 06:12 spiderworm

Does that solve the problem now?

zxb5102 avatar Dec 06 '17 12:12 zxb5102

I have a similar problem with my project

zxb5102 avatar Dec 06 '17 12:12 zxb5102

I have a partially working solution in a branch I've not yet pushed, but it still has some major issues. It's a tricky one. Maybe I should push it if other people are interested in helping?

liabru avatar Dec 06 '17 15:12 liabru

@liabru Sounds like that might be a good idea? Along with a brief description of your approach, and of the problems that still need solving might be helpful.

spiderworm avatar Dec 06 '17 18:12 spiderworm

In my use case, I managed to work around it by listening to collisionEnd event, check if the bodies were forced out of the viewport. If so, re-position that body to bring it back. (this is good enough for my use case because I only need to make sure no objects can get thrown out of the bounding rectangles.

Hope this helps.

billylo1 avatar Dec 14 '17 04:12 billylo1

Is this ever going to be continued?

qwertyquerty avatar Apr 04 '18 23:04 qwertyquerty

I was also wondering about that @qwertyquerty. Any progress on implementing CCD @liabru ?

pixelscripter avatar Apr 10 '18 12:04 pixelscripter

Also interested in seeing this feature.

soulofmischief avatar Apr 23 '18 06:04 soulofmischief

Any progress on implementing CCD

whaqzhzd avatar May 16 '18 12:05 whaqzhzd

object passing through walls,I met this problem, too. I'm really looking forward to the problem being solved

cheneyweb avatar Jun 20 '18 05:06 cheneyweb

^^^ Me too

7ammer avatar Jul 02 '18 03:07 7ammer

Is there any way?

yungzhu avatar Aug 17 '18 02:08 yungzhu

EDIT 2: https://gist.github.com/fabienjuif/a7d9fc3e34e23f6000bcfc185dc0e341

EDIT: I fall into FPS issues, the engine run objects faster on 60FPS than on 30FPS. So don't try that at home :(


I did this trick for now:

  // engine
  // - run the engine several times, so we have the feeling the game is fast
  // - also, this avoid collision detecting issue since CCD is not implemented yet in matter-js
  let lastLoop = Date.now()
  for (let i = 0; i < RERUN; ++i) {
    Engine.update(engine, i === 0 ? delta : (Date.now() - lastLoop))
    lastLoop = Date.now()
  }

And divide all my velocities by the RERUN amount :) It works, but I assume this is less performant

fabienjuif avatar Aug 18 '18 13:08 fabienjuif

+1

osfa avatar Oct 04 '18 15:10 osfa

Question: could a bounty help push this issue forward? We'd be happy to contribute.

maltenuhn avatar Oct 04 '18 16:10 maltenuhn

This really should be completed, considering it's such a big issue, and it's been open for so long.

qwertyquerty avatar Nov 01 '18 03:11 qwertyquerty

Is there any work in-progress to address tunneling issues?

stefannew avatar Feb 26 '19 19:02 stefannew

I'd also like to see the tunneling issues resolved.

notchris avatar Mar 29 '19 17:03 notchris

Any updates?

dzcpy avatar Oct 05 '19 08:10 dzcpy

Can we throw money at this issue? I'm writing "A Book About Hype" and Hype uses Matter.js as its Physics engine. I was writing about the CCD issue and I realized that I could add a blurb where people can send money to fix this problem. Maybe GitHub sponsors works?

michael-garofalo avatar Apr 23 '20 20:04 michael-garofalo

I switched to Planck.js at last. It worked well, just lack of documentation. Matter is way more intuitive. But this bug is too annoying

dzcpy avatar Apr 28 '20 16:04 dzcpy

it's kind of amazing to receive updates on this issue like 4 years later, reminding me of where I was in life while working on this. Trump hadn't been elected, it was a simpler time.

Anyway it would be great if the maintainer or others could give any ideas or an outline of what a solution might be. seems like it would reduce friction for finding someone to work on it (bounty or not).

On Tue, Apr 28, 2020 at 12:04 PM dzcpy [email protected] wrote:

I switched to Planck.js at last. It worked well, just lack of documentation. Matter is way more intuitive. But this bug is too annoying

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/liabru/matter-js/issues/5#issuecomment-620700340, or unsubscribe https://github.com/notifications/unsubscribe-auth/AARQDMXKEN4JDXMSR3U3JGLRO35CBANCNFSM4AMWL26A .

joshkpeterson avatar Apr 28 '20 16:04 joshkpeterson

@liabru Helppppppppppp

notchris avatar Apr 28 '20 19:04 notchris

Is it not possible to just copy/paste code from a JavaScript port of Box2D like PlanckJS to solve this issue?

Feavy avatar May 02 '20 09:05 Feavy

@Feavy Something like that, but porting isn't super easy.

notchris avatar May 02 '20 20:05 notchris

it's kind of amazing to receive updates on this issue like 4 years later, reminding me of where I was in life while working on this. Trump hadn't been elected, it was a simpler time. Anyway it would be great if the maintainer or others could give any ideas or an outline of what a solution might be. seems like it would reduce friction for finding someone to work on it (bounty or not). On Tue, Apr 28, 2020 at 12:04 PM dzcpy @.***> wrote: I switched to Planck.js at last. It worked well, just lack of documentation. Matter is way more intuitive. But this bug is too annoying — You are receiving this because you commented. Reply to this email directly, view it on GitHub <#5 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AARQDMXKEN4JDXMSR3U3JGLRO35CBANCNFSM4AMWL26A .

So, hopefully most of you guys would choose to jump ship as long as you still can. Don't let yourself sink into despair for another 4 years.

dzcpy avatar May 03 '20 03:05 dzcpy

+1

jtoy avatar May 14 '20 13:05 jtoy

I ran into this tunneling problem with matter.js and eventually abandoned it in favor of box2d.js and haven't had a problem since. box2d.js's API is less nice because it's directly compiled from C++ using Emscripten but it wasn't hard to switch. Highly recommended.

huy-nguyen avatar Jun 03 '20 04:06 huy-nguyen

it's already 2021, we are almost in the middle of the year, do we have any progress with CDD ?

Loque18 avatar Jun 13 '21 21:06 Loque18

Be the change in the world you wish to be, peeps! Any Pull Requests on this issue?

WesWedding avatar Jun 22 '21 21:06 WesWedding

No, switching to box2d is the right move

dzcpy avatar Jun 22 '21 22:06 dzcpy

There seemed to be a hack on Stack Overflow that worked with 0.12.0 and earlier.

mulhoon avatar Dec 16 '21 21:12 mulhoon

No, switching to box2d is the right move

Tried and failed to solve the issue. The problem is critical. I don't know if I should wait or jump ship. The tools and docs in matter.js are so much better than box2d.js.

bombzj avatar Feb 14 '22 14:02 bombzj

No, switching to box2d is the right move

Tried and failed to solve the issue. The problem is critical. I don't know if I should wait or jump ship. The tools and docs in matter.js are so much better than box2d.js.

For me box2d works perfectly in my projects. I used Planck.js though. It's true that matter.js's documentation is way better, but I can't get it work

dzcpy avatar Feb 14 '22 14:02 dzcpy

Wait? This issue is over 6 years old lol

On Mon, Feb 14, 2022 at 3:47 PM Jacob @.***> wrote:

No, switching to box2d is the right move

Tried and failed to solve the issue. The problem is critical. I don't know if I should wait or jump ship. The tools and docs in matter.js are so much better than box2d.js.

— Reply to this email directly, view it on GitHub https://github.com/liabru/matter-js/issues/5#issuecomment-1039163044, or unsubscribe https://github.com/notifications/unsubscribe-auth/AARQDMTSWITWYQJEGB7YLR3U3EH3VANCNFSM4AMWL26A . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you commented.Message ID: @.***>

joshkpeterson avatar Feb 14 '22 15:02 joshkpeterson

No, switching to box2d is the right move

Tried and failed to solve the issue. The problem is critical. I don't know if I should wait or jump ship. The tools and docs in matter.js are so much better than box2d.js.

You could open a PR instead of waiting.

stefannew avatar Feb 14 '22 16:02 stefannew

The simplest solution if you need fast moving or thin bodies is to sub-step, it's robust and not all that expensive now and you get higher quality results all round.

You can even dynamically increase your substeps for just a few frames when you detect fast moving bodies, if performance was an issue (and you don't mind possibly inconsistent results, like with a dynamic timestep).

Until I've finished adding substeps as a feature into Matter.Runner (it's a bit tricky to handle all possible framerates, plus a few other things for the general case), here is a very simplified example (that assumes fixed 60fps) to demonstrate:

const delta = 1000 / 60;
const subSteps = 3;
const subDelta = delta / subSteps;

(function run() {
    window.requestAnimationFrame(run);
    for (let i = 0; i < subSteps; i += 1) {
      Engine.update(engine, subDelta);
    }
})();

As well as sub-steps also consider:

  • make thin bodies thicker (but can render them thinner similar to this example)
  • apply a max speed limit to bodies (e.g. similar to this example)
  • avoid large timesteps (<= 16.666ms is recommended)
  • ray cast along body velocity and clamp velocity to e.g. 50%

Let me know if that helps - I realise this isn't so obvious unless you're very used to game dev!

liabru avatar Feb 25 '22 10:02 liabru

Same Issue while working with Matter.js in React Native! Changing the body size and velocity or obstacle thickness does not solve the issue.

hossein4bedi avatar Apr 16 '22 02:04 hossein4bedi

I switched from using applyForce to setVelocity, fixed the tunneling bug in my app.

        Matter.Body.setVelocity(ball, { x: ball.velocity.x + 20, y: ball.velocity.y - 20 });
        // Matter.Body.applyForce(ball, ball.position, { x: 0.05, y: -0.05 });

nightness avatar Jun 23 '22 20:06 nightness

Is there some sort of path tracing collision detection? Say if object A moves from position X to position Y, create a line (X1, X2, Y1, Y2) and check if the line intersects with the object lines? My body seems to be phasing through other bodies despite the speed not being that quick.

Or to be precise, when applying force to a body near to another body it phases through, maybe I have another problem?

Anatoly03 avatar Jul 14 '22 08:07 Anatoly03

@Anatoly03 see the last point in https://github.com/liabru/matter-js/issues/5#issuecomment-1050738814 about raycasting - to avoid some of the worst cases that approach seems reasonable (especially for user controlled bodies), but generally difficult to make robust. Again I'd strongly recommend using sub-stepping as mentioned in that comment.

liabru avatar Jul 19 '22 09:07 liabru

@Anatoly03 see the last point in #5 (comment) about raycasting - to avoid some of the worst cases that approach seems reasonable (especially for user controlled bodies), but generally difficult to make robust. Again I'd strongly recommend using sub-stepping as mentioned in that comment.

image

Is it possible to creating an extended polygon of the movement by tracing the nodes, then check for objects intersecting this polygon?

Anatoly03 avatar Jul 19 '22 17:07 Anatoly03