开发者

Box2d.js with Processing.js

Recently I have been furthering my knowledge of Javascript, by combining the Processing.js and Box2D.js libraries to make some neat browser-based simulations.

With my current idea, I am trying to allow the user to click and drag a shape, and then let it drop once the mouse is released. So far I have been able to figure out how to use the b2MouseJoint object to manipulate a body with mouseX/mouseY coordinates, but it doesn't quite work to the full extent.

All that happens when a shape is clicked is it gets pinned and revolves around what ever mouseX/mouseY point was current at the time of the click.

void mousePressed(){
     for(int i = 0; i < circles.size(); i++){   
        //Get body objects from ArrayList
        var obj = circles[i]; 

        // Retrieve shapes from body
        var innerShape = obj.GetShapeList();
        var rad = innerShape.m_radius;

        // Create mouseJoint and add attributes
        var mouseJoint = new b2MouseJointDef();
开发者_Go百科        mouseJoint.body1 = world.GetGroundBody();

        // Detect body
        if(dist(mouseX,mouseY,obj.m_position.x,obj.m_position.y) < rad){
           Vec2 p = new b2Vec2(mouseX,mouseY);

           mouseJoint.body2 = obj;

           mouseJoint.target = p;
           mouseJoint.maxForce = 10000.0f * obj.GetMass();
           mouseJoint.collideConnected = true;
           mouseJoint.dampingRatio = 0;
           mouseJoint.frequencyHz = 100;
           world.CreateJoint(mouseJoint);      
        }
   }    
}

So basically my question is, how can this be written so the Body/Shape follows my mouse's coordinates while I have the mouse held down, instead of just pinning the shape in place.

Cheers


Basically all you have to do is add the code you're using now to set the coordinate in mousePressed to a mouseDragged() method, as well, as this is the event method that gets called while the mouse is moved with one or more buttons depressed:

void mouseDragged()
{
  // update obj with mouseX and mouseY in this method
}

You may also want to do a bit more administration by setting up "initial click" mark variables during mousePressed(), updating a set of "offset" variables during mouseDragged() and committing the offsets to the marks in mouseReleased(), so that you can do things like snapping back to the original position, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜