Physics icon indicating copy to clipboard operation
Physics copied to clipboard

bounds

Open julapy opened this issue 9 years ago • 3 comments

hi,

ive started using your Physics lib to take advantage of the spring functionality and because its so light weight. normally ive used box2d which has the ability to set the bounds so the particles can be contained within the screen.

what do you recommend as being the best way of containing particles within the screen with Physics?

just thought id ask first in case you have a good solution to this...

cheers in advance!

julapy avatar Feb 22 '16 03:02 julapy

Thanks for the post @julapy! Love your work :+1:

Unfortunately the library doesn't have any constraints to do something like this out of the box. However, for containing particles within a box you can always reverse the direction of the velocity like so:

var particle = physics.makeParticle(mass, 0, 0);
physics
  .onUpdate(function() {
    if (particle.position.x > width || particle.position.x < 0) {
      particle.velocity.x *= -1;
    }
    if (particle.position.y > height || particle.position.y < 0) {
      particle.velocity.y *= -1;
    }
  })
  .play();

Let me know if working example would be better. Hope this helps!

jonobr1 avatar Feb 22 '16 04:02 jonobr1

hey Jono, thanks for the quick reply. and im a big fan of your work also!

what i noticed when using box2d in the past, its doesn't like when you mess around with position and velocity values directly... it kind of messes up the physics calculations and it looses that nice, continuous flow...

i was thinking that it might be the case here also... but after playing with Physics for a bit, it seems to be a lot more forgiving, so thats a good :)

im also going to try another approach by adding a attraction force to the centre when the particle goes out of bounds. this way it won't bounce off the walls but it should smoothly return into the bounds. thats the theory anyway... lets see how it behaves.

thanks again for your reply!

julapy avatar Feb 22 '16 04:02 julapy

Nice!

Ah yes, if you don't need a distinct "bounce" off the edge then an attraction should do the trick. Let me know how it goes, happy to help further!

jonobr1 avatar Feb 22 '16 04:02 jonobr1