Search code examples
javascriptcannon.js

CANNON.js: check if a body is being constrained


I've been trying to make a multiplayer game using javascript (most of which is on the server, using Node.js); one of the core mechanics I want to make is that players will be able to design their own fighting style (right down to how they swing their sword etc). Problem is that I can't find any simple way of constraining players' movements.

I first tried to write a method that checks then clamps the player's style so it doesn't look like they're breaking every limb simultaneously, but that didn't really work. I then found the wonderful CANNON.ConeTwistConstraint, but after looking through the documentation I've found that CANNON.js's constraints don't seem to have any sort of built-in function for just testing whether two bodies are exceeding the constraint's limits. I've thought about having my game just create objects in a separate simulation and check whether a force is being applied to either object, but I'm not sure about how to go about this, or if there's a better way.

Is there a simple/easier solution to my problem? If not, what would be the least CPU-intensive way of implementing the above?


Solution

  • You can manually check if the ConeTwistConstraint is hitting its limit. If you have a look at the method CANNON.ConeEquation.prototype.computeB, you can see that it computes the constraint violation, "g", using cos() and a dot product. You can simply do the same with the following code.

    var eq = coneTwistConstraint.coneEquation;
    var g = Math.cos(eq.angle) - eq.axisA.dot(eq.axisB);
    if(g > 0) {
        // Constraint limit exceeded
    } else {
        // Constraint is within limits
    }
    

    Using the same strategy, you can check if the twist limit is exceeded. Since the twist equation is a CANNON.RotationalEquation, the code becomes:

    var eq2 = coneTwistConstraint.twistEquation;
    var g2 = Math.cos(eq2.maxAngle) - eq2.axisA.dot(eq2.axisB);