Search code examples
c++cocos2d-xbox2drevolute-joints

Fire event when reach certain angle in revolute joint


I need to develop cannon game using box2d and cocos2dx. Cannon is divided into two parts

  • Base which is fixed in the ground and doesn't move.

    b2WeldJointDef basePlatformWeldJointDef;
    basePlatformWeldJointDef.Initialize(base->getBody(), weaponPlatform->getBody(),weaponPlatform->getBody()->GetWorldCenter());
    basePlatformWeldJointDef.collideConnected = false;
    basePlatformWeldJoint = m_world->CreateJoint(&basePlatformWeldJointDef);
    
  • Arm which is fixed in the base with a RevoluteJoint.

    b2RevoluteJointDef armJointDef;
    armJointDef.Initialize(base->getBody(), arm->getBody(), m_loader->pointsToMeters(ccp(armPosition.x-(arm->getContentSize().width*WeaponScale/4),armPosition.y)));
    
    armJointDef.enableMotor = true;
    armJointDef.enableLimit = true;
    armJointDef.motorSpeed  = 0;
    armJointDef.lowerAngle  = CC_DEGREES_TO_RADIANS(0);
    armJointDef.upperAngle  = CC_DEGREES_TO_RADIANS(0);
    armJointDef.maxMotorTorque = 2;
    
    armJointDef.collideConnected = false;
    
    cannonRevoluteJoint = (b2RevoluteJoint*)m_world->CreateJoint(&armJointDef);
    
  • The cannon should calculate the angle that will fire to, and this is calculated correctly. Using the revolutJointObject->setLimits(lowerAngle, higherAngle) here i use the lowerAngle and the higherAngle both are the desired angle so the arm moves to desired angle directly without motion.

  • Then i needed to move the arm not just change its angle, so i set the lowerAngle and higherAngle with the old angle and desired angle depending which will be the lower and the which will the higher, and changed the motor speed of the RevoluteJoint

  • The problem is that i need a callback method which fires when the revolute joint reaches to a certain angle or when the motor speed reaches Zero assuming that when the arm reaches the limit angle will stop and the motor speed will be Zero.

I have searching in SO and i found This Solution which calculates the angle each step, this can be used but it needs more calculations that i feel lazy to do.

Does the callback method for notifying motor speed or certain angle has been reached exists ?


Solution

  • Schedule a function to check your conditions on each frame. When you don't need the checks any more - unschedule the selector, then reschedule when needed again. As far as I know there are no callbacks for your exact task.