Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot SetTarget of b2MouseJoint #126

Open
Jennics-SG opened this issue May 5, 2024 · 0 comments
Open

Cannot SetTarget of b2MouseJoint #126

Jennics-SG opened this issue May 5, 2024 · 0 comments

Comments

@Jennics-SG
Copy link

Jennics-SG commented May 5, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant