开发者

MouseJoint not properly working

开发者 https://www.devze.com 2023-03-30 14:30 出处:网络
I have been trying to use a MouseJoint to move a piece wherever the user touches. But the piece, being affected by the joint, behaves strangely, never reaching the point. This is the code (x and y are

I have been trying to use a MouseJoint to move a piece wherever the user touches. But the piece, being affected by the joint, behaves strangely, never reaching the point. This is the code (x and y are already converted to 'physical' units):

MouseJointDef mj_def;
MouseJoint mj = null;
Body mj_gbody;

p开发者_StackOverflow中文版ublic void move(float x, float y)
{
    if(mj == null)
    {
        BodyDef mgbd = new BodyDef();
        mj_gbody = wrld.createBody(mgbd);
        //
        mj_def = new MouseJointDef();
        mj_def.bodyA = mj_gbody;
        mj_def.bodyB = body;
        mj_def.collideConnected = true;
        mj_def.maxForce = 20.0f * body.getMass();
        //mj_def.target.set(x,y);

        mj = (MouseJoint)wrld.createJoint(mj_def);
        body.setAwake(true);
    }

    mj.setTarget(new Vector2(x, y));
}

I was looking for some way to establish the anchor point in the BodyB, as the 'strange behaviour' that I mentioned seems to make the body gravitate around the established point (an orbit twice the width of the object), as if the anchor point was outside of the body (hexagon shaped, btw). But I don't see any way of doing so in libgdx.

Does anybody know what I am doing wrong? Thank you in advance!


Well, MouseJoint was working properly, I just misunderstood how MouseJoint works.

As it is clearly seen in the Box2d testbed, MouseJoint is used for dragging after selecting an object. Therefore, the anchor is assigned in the first target.set.

As I wanted to move the center of the object to the place where the mouse was (or the user touched), a mj_def.target.set(body.getPosition().x + 2.0f, body.getPosition().y + 1.0f); (the object is 4.0f by 2.0f) in the initialization solved the problem. Also, it may be not the best Joint for my intentions (to move an specific object to one place in the screen).

0

精彩评论

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

关注公众号