kripken / box2d.js

Port of Box2D to JavaScript using Emscripten
1.33k stars 196 forks source link

Cannot SetTarget of b2MouseJoint #126

Open Jennics-SG opened 5 months ago

Jennics-SG commented 5 months ago

Tried creating a draggable sprite using b2MouseJoint but the joint had no Target attribute unless manually added, also meaning SetTarget is not a function of b2MouseJoint. Found it in source code but wont work in use.

    // Drag Start
    private physicsDragStart(e: MouseEvent){
        // Create tiny entity at mouse x,y
        const draggerOps = {
            bodyType: "Static",
            shape: "box",
            density: 0,
        }
        this._dragger = new Entity(
            e.x, e.y,
            1, 1,
            draggerOps, this._physicsEntity.engine,
            this._physicsEntity.layer, "dragger"
        );

        // Create distance joint & attach to entity
        const jd = new this._physicsEntity.engine.b2d.b2MouseJointDef();
        jd.bodyA = this._dragger.body;
        jd.bodyB = this._physicsEntity.body;
        jd.collideConnected = true;

        const mouseWorldPoint = this._physicsEntity.engine.coOrdPixelToWorld(e.x, e.y);
        jd.target.Set(mouseWorldPoint.x, mouseWorldPoint.y);

        jd.maxForce = 5000 * this._physicsEntity.body.GetMass()
        jd.stiffness = 1;
        jd.dampingRatio = 0.9

        this._joint = this._physicsEntity.layer.world.CreateJoint(jd);
    }

    // Drag Move
    private physicsDragMove(e: MouseEvent){
        // Move distance joint to mouse pos
        if(!this._joint || !this._physicsEntity || !this._dragger) return

        // Move dragger body
        const mouseWorldPoint = this._physicsEntity.engine.coOrdPixelToWorld(e.x, e.y);

        this._dragger.body.SetTransform(mouseWorldPoint);

        this._joint.SetTarget(mouseWorldPoint);
    }

    // Drag End
    private physicsDragEnd(e: MouseEvent){
        // Destroy Distance Joint
        this._physicsEntity?.layer.world.DestroyJoint(this._joint);
        this._joint = null;
    }

You can give the MouseJoint a target attribute by using mouseJoint.target = new b2Vec2() and update it with the same sort of method but doing this means that the box isn't dragged, rather suspended from where the original click was.