Search code examples
libgdxbox2drevolute-joints

How to control Revolute joint using input button?


I am trying to rotate a body connect via revolute joint, when space bar button is pressed in my desktop.it is working fine when i put all the condition in create, but not working on pressing space bar button. here is my create method

            ballBody =createBall();//first body to the joint
            rectBody=createRect();//second body to the joint

            revoluteJointDef = new RevoluteJointDef();
            revoluteJointDef.initialize(ballBody,rectBody,new Vector2(0,0));
            revoluteJointDef.lowerAngle=0;
            revoluteJointDef.upperAngle=0.785f;
            revoluteJointDef.localAnchorA.set(2,0);
            revoluteJointDef.localAnchorB.set(0,6);
            revoluteJointDef.collideConnected=false;

            revoluteJointDef.lowerAngle=-0.734f;
            revoluteJointDef.upperAngle=0.735f;
            revoluteJointDef.maxMotorTorque=100f;
            revoluteJointDef.motorSpeed=-12.6f;
            revoluteJointDef.referenceAngle=0f;
            revoluteJointDef.enableLimit=true;
            joint = world.createJoint(revoluteJointDef);

and i am enabling motor after pressing space bar button like this

  public boolean keyDown(int keycode) {
        if(keycode== Input.Keys.SPACE) {
                   hit();  // call to hit function
        }

here is hit function

  private void hit(){
        revoluteJointDef.enableMotor=true;
        }

and my render method is like this

 public void render(float delta) {
        Gdx.gl.glClearColor(0.5f, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        game.batch.setProjectionMatrix(camera.combined);
        world.step(1f/60f, 6, 2);
        debugRenderer.render(world, camera.combined);
        game.batch.begin();
         game.batch.end();
    }

please help me out with any suggestion.


Solution

  • I found mistake in your Create method last line it should be like

    revoluteJoint=(RevoluteJoint)world.createjoint(revolutejointDef);
    

    and in hit method or else than create method use revolutejoint instead revolutejointDef

    revoluteJoint.enableMotor=true;