How to create repulsive forces for spheres


I would like to create spheres with “electric charges” such that they would repel if they are the same charge and attract if opposite. I haven’t found a way to do this with the CannonJS API and was wondering if anyone had some ideas.

Ideally, I would like to add a function to the physics engine called on every update that:

  1. determined the effective “electric field” caused by the particles as a function of space
  2. and from that determine for each sphere the force felt by that sphere in response to that field.

Thanks for you help!

Hello and welcome to the forum !!!

I wonder if you should first try to do a playground with all the related code before trying to move it further.

My guess is you could compute the “electric field” and from this use impulse to translate it into a “moving” force.

Some way better people than me will probably jump in the thread soon like @trevordev for instance

Hi, I really don’t know what the proper way of working with physics is, but this works: :smiley:

Edit: (had the attraction reversed)


@sebavan and @Gijs – thank you for your replies. @Gijs – that’s a perfect playground example. Thanks!