Jump to content

  • Log In with Google      Sign In   
  • Create Account


Member Since 29 Mar 2012
Online Last Active Today, 07:48 AM

Topics I've Started

Polygon vs polygon contact points clipping headache

21 July 2014 - 01:31 PM

Hi there,


i am currently in the process of implement a algorythm to calculate 2D contact points for two convex polygons (2 oriented boxes for now).

The basic idea is to clip the incident polygon face (line segment) to the reference polygon side face planes and my implementation goes as follow:


1.) Use separating axis theorem to get the collision normal and penetration depth.


2.) Determine which is the incident and reference body (Reference is body A and incident is body B always)


3.) Find the support point for the incident body along the inverted normal (Incident support)


4.) Find the support point for the reference body along the normal (Reference support)


5.) Find the incident edge (line segment) from the incident support point by finding the second vertex which is most perpendicular to the normal from the next or previous vertex.


6.) Find the reference edge (line segment) from the reference support point by finding the second vertex which is most perpendicular to the normal from the next or previous vertex.


7.) Get perpedicular left and right normal (right is (-y, x) left is (y, -x))


8.) Construct two planes for the the reference edge vertices (Plane 1 distance = vertex dot right normal, Plane 2 distance = vertex dot left normal)


9.) Clip the incident line segment against the two planes


10.) Keep only the vertices which penetrates or touches the reference polygon - thats the contact point(s)


I have already implemented part 1-8 and these works fine so far, but i am really unsure about the clipping planes.

Is it correct to just use the perpendiculars of the normal which located on the reference edge vertices? Or is there some better/faster way.


Of course the last thing i need to do is the actual clipping, but this seems to be very straight forward - should be easy to implement it right?


For better explanation i made two images - see attachments (For the first case the clipping would do nothing, because the vertices are on the other side of the plane, therefore my contact points whould just be the incident edge vertices.)


Would be really great is you guys can help me out with that.




Entity component system and physics

23 June 2014 - 02:01 PM

Hi there,


i am in the phase to adding my 2d physics engine over to my freshly created entity component system and have some design headaches.


It is a simple entity component system, which has "Components" which are just containers and "Systems" which may require n-components and can update or draw a list of entities. There is a component registration which register new component classes (to support unlimited components) who creates new handles and cache this by the class name. Then we have the mighty manager which handles the initialization / update / draw of the systems, keeps a entity list + a list for each system and gets notified when components are added or removed from an entity. An entity is just an component container which do have only the methods for adding/removing and retrieving components. Thats basically it - nothing too fancy and works so far.


But, i have a problem - my current physics engine uses a rigidbody class, which contains all the required properties (like position, velocity, mass, shape etc.) to work with and my entities on the other hand do just contains the "containers" of this properties - some cannot be used (simple types, like numbers, floats) as references which are no references/pointers at all - because its implemented in javascript (numbers are no references).


Is there a good way to integrate a rigidbody/physics engine in a entity component "system"?




My current naiive approach is:


Splitting the rigidbody into multiple components:


- PositionComponent (position vector only)

- VelocityComponent (velocity, angular velocity and both damping factors)

- TransformComponent (rotation angle and transformation matrix)

- MassComponent (mass, inertia and both invert parts of it + density factor)

- ShapeComponent (contains just a reference to actual shape class - like CircleShape which just contains the radius and the massCompute stuff)

- PhysicsComponent (contains all the rest properties from the rigidbody like force, torque, tmp acceleration, next position, friction and restitution coeffs)


Copying code over from my physics engine into the new physics system and change this to use the entity and components like this (seems to be ugly):

        PhysicsSystem.prototype.update = function(entities, dt){
            var i, entity, posComp, velComp, massComp, phyComp, transComp, gravityComp;

            Profiler.begin("Physics step");

            // Add forces to dynamic bodies
            Profiler.begin("Integrate forces");
            var gravityForce = Vec2Pool.get();
            for (i = 0; i < entities.size(); i++) {
                entity = entities.item(i);
                velComp = entity.getComponent(this.velHandle);
                massComp = entity.getComponent(this.massHandle);
                phyComp = entity.getComponent(this.physicsHandle);
                gravityComp = entity.getComponent(this.gravityHandle);
                if (!massComp.isStatic() && gravityComp != null) {
                    math.vec2MultScalar(gravityForce, gravityComp.gravity, massComp.mass);
                    math.vec2Add(phyComp.force, phyComp.force, gravityForce);

            // Integrate velocities
            Profiler.begin("Integrate velocity");
            for (i = 0; i < entities.size(); i++) {
                entity = entities.item(i);
                posComp = entity.getComponent(this.posHandle);
                velComp = entity.getComponent(this.velHandle);
                massComp = entity.getComponent(this.massHandle);
                phyComp = entity.getComponent(this.physicsHandle);
                if (!massComp.isStatic()) {
                    this.integrateVelocity(phyComp, massComp, posComp, velComp, dt);
                } else {
                    math.vec2Clone(phyComp.nextPosition, posComp.position);

which is orginally this:

        PhysicsEngine.prototype.step = function (dt) {
            var i, body;

            Profiler.begin("Physics step");

            // Add gravity force to dynamic bodies
            Profiler.begin("Integrate forces");
            var gravityForce = Vec2Pool.get();
            for (i = 0; i < this.world.size(); i++) {
                body = this.world.item(i);
                if (!body.isStatic()) {
                    math.vec2MultScalar(gravityForce, this.world.gravity, body.mass);

            // Integrate velocities
            Profiler.begin("Integrate velocity");
            for (i = 0; i < this.world.size(); i++) {
                body = this.world.item(i);
                if (!body.isStatic() && body.awake) {
                } else {
                    math.vec2Clone(body.nextPosition, body.position);

The only thing which comes to my mind, is to create all the bodies for each entity which references all the properties from the components directly (i could do that because i have an notification system already) - which would force me to change my rigidbody class to use only property types which can be used as references. Other idea is to create a rigidbody component - which justs includes all the properties from all required components (of courses needs also be references as well)


Another things which bugs me is the number of components - is it a good idea to separate the rigidbody properties like this or is it better to use a single component (RigidbodyComponent) which just have all the properties from the original one, but would require that the position component uses the rigidbody position to not need to syncronize positions..... ahhh too much pain ... i have an headache now...

Explosive tangent impulses causes extreme rotation

17 June 2014 - 02:51 PM

Hi there,


i got my html5/javascript 2D Sequential-Impulse based physics engine working - yay - but got issues with some weird behaviours :-(

It looks stable, but contacts creates explosive tangent impulses which increases the angular velocity.


Here are a video of some stacking circles which shows the weird effect (after forcing the collapse, the circles rotation goes faster and faster.


Another video showing the issue on a smaller scale:


I nearly use the same approach as box2d - except i added the position correction directly to the velocity bias. The friction code is identical and should be a direct port with one minor difference: i calculate the tangent normal once in the contact initialization - because the normal does not change for each contact/frame.


Source for contact solver + initialization:



No idea what causing these problems. I also tried to use a static/dynamic friction method, but had some more worse effects.


Would be really great, if you can help me to identify the issue.


Thanks in regards,


Wrong result for ported SPH Simulation

01 July 2013 - 11:51 PM

Hi there,


i am currently trying to port a working SPH - Smoothed Particle Hydrodynamics 2D implementation to Javascript with the simplest methods possible. Original code see here: http://www.opentk.com/node/377


After some days i got some results which moves particles but behaves really weird - Particles just pushes other particles away and does not behave correctly. The main problem is - SPH is based on heavy maths and i dont understand the details at all - Therefore fixing issues is really hard. Dont get me wrong, i have some experience with vector maths, collisions and response, see this demo: http://root.xenorate.com/final/physics/circles.html (Circle/Plane Collision with TOI handling and collision response)

Therefore i understand vector arithmetic a little, but SPH is just a little to hard to figure out myself. Also i made a fully working 3D Fluid Simulation in the past, but using PhysX as a Physics Engine: See this demo i made: http://www.youtube.com/watch?v=eUbwxTE38TY

Now i wanted to try to make this myself, without using a physics engine at all.

Please have a look at my javascript SPH port: http://jsfiddle.net/gRUKg/1/


Currently my implementation does not handle every aspect from the original source, i use a diffent spatial grid technique and the viscosity and adjust distance code is disabled (Not required to get this working)


It would be really great if you can help me to get this thing working. I really want to understand the details behind it, for tuning the properties and improve it. Of course i read several SPH papers, but i cannot understand this at all.


Thanks in regards,


What is wrong with my SAT implementation?

10 March 2013 - 12:39 PM

Hi everybody,


i have implemented discrete SAT (Separating Axis Theorem) in the past successfully.

Therefore i have now remade this to fix the "fast moving issue" - calculate the time when the collision first happens - to get a value for scaling the velocity to remove the penetration in the first place.


What i basically do is to test two OBB with two fixed axis of (1, 0) and (0, 1) with the following algorythm:


- Get the relative position (distance) between the 2 OBBs (pA - pA)

- Get the relative velocity between the 2 OBBs (vA - Vb) - Just to remove the second velocity to make the second one static.

- For loop over the two axes

- Project the relative position onto the axis to get an offset based on current axis

- Project A onto current axes and get min/max projection

- Add the offset to projection of A

- Project B onto current axes and get min/max projection

- Calculate distances between min/max projections of A and B (d0, d1)

- Calculate time enter and time leave factor by divide both distances by projected velocity on axis

- Swap time enter with time leave if required (Time enter must always be smaller than time leave)

- Get the highest overlap to skip out collisions which not happens or are too late

- Time Enter is the factor used to fix the velocity.


These steps are implemented a simple JSFiddle demo i have written to visualize the entire process, see here:


Now what the problem is: There are something missing on it, because the visualized velocity/corrected projection is wrong in some cases (Inverted for Y Axis) and i havent found a solution yet to find the correct single time enter/leave factor. What i want in the end is a "Time of impact" value which can be used to fix the velocity, to project the box on the other box without penetration.



It would be really great if you can help me to fix these problems.