javascripthtmlkineticjsbox2dweb

Using KineticJS along with box2dweb


How do I use kineticJS along with box2dweb so that I can have collision detecting possible? Like, how can I put a circular boundary around an image rendered through kineticJS and apply physics through box2dweb?

Are there any good tutorials on this or any codes that can help me? Or is there any efficient way that I can do collision detection with kineticJS itself?


Solution

  • What you do is:

    1. Set up a box2d “world” – think of the world as a room on earth (or any other planet)

    2. Add “bodies” to the world – bodies are moving or stationary objects that behave according to the physics you have assigned to them.

    3. For each box2d body, assign a kineticJs “skin” – skins are “pretty” kineticJs shape objects that will be drawn on the canvas by kineticJs. For example, in a game a skin might be a soccer ball.

    4. Put the box2d world in motion and listen for the box2d “tick” event – the tick event is fired when box2d has figured out the physics that occurred during your specified length of time. At this point box2d knows the position and rotation of each box2d body in the box2d world.

    5. In the box2d tick event, check the position/rotation of each box2d body and draw the kineticJs skin at the same position/rotation at the box2dbody.

    There is a very good example at: http://www.luxanimals.com/blog/article/combining_easel_box2d

    This example uses easelJs to draw on the canvas, but the convertion to the kineticJs library is very straightforward – the exact same concepts apply.

    [edited to give additional information]

    Also, if you don't need all the physics in box2d, here is a very simple 2-circle collision test using kineticJs.

    function CirclesAreColliding(circle1,circle2){
        var dx = circle2.getX() - circle1.getX();
        var dy = circle2.getY() - circle1.getY();
        if( Math.sqrt( dx*dx + dy*dy ) <= ( circle1.getRadius() + circle2.getRadius() ) {
            return true;
        }
        return false;
    }