[Cocos2d-x C++] Keeping constant velocity on physics body.

  • EnesOzdemir
    Likes 0

    Problem Description

    Hello,

    I am having issues keeping constant velocity on a few physics bodies.  I am using the built in physics for cocos2d-x instead of box2d.  I remember you guys saying in one of your videos that you had the same issue with your Glo Breaker game.  I’ve used setVelocity but over time the objects slow down while bouncing inside a set boundary box.  I would also like to know if it is possible to have a constant force applied to the body in the direction the body is travelling, such as acceleration.  

    Thanks.

  • Sonar Systems admin
    Likes 0

  • EnesOzdemir
    Likes 0

    Hi Sonar

    I’ve tried the above in conjunction with 

    bool GameScreen::onContactBegin(PhysicsContact& contact)
    {
        auto a = contact.getShapeA()->getBody();
        auto b = contact.getShapeB()->getBody();
        if (( 2 == a->getCollisionBitmask() && 2 == b->getCollisionBitmask() )
            || ( 2 == a->getCollisionBitmask() && 2 == b->getCollisionBitmask() ))
        {
            return false;
        }
        if ((2 == a->getCollisionBitmask() && 1 == b->getCollisionBitmask())
            || (1 == a->getCollisionBitmask() && 2 == b->getCollisionBitmask()))
        {
            //GoToGameOverScene(this);
            return false;
        }
        if ((3 == a->getCollisionBitmask() && 1 == b->getCollisionBitmask())
            || (1 == a->getCollisionBitmask() && 3 == b->getCollisionBitmask()))
        {
            //GoToGameOverScene(this);
            return true;
        }

        // save the velocity, ignore the direction of velocity, only save the length
        float* v = new float[2];
        v[0] = a->getVelocity().length();
        v[1] = b->getVelocity().length();
        contact.setData(v);

        return true;
    }

    The above throws an exception at  “a->setVelocity(va * v[0]);”, as done in your solution.  But when I comment out the collision detection and just leave the bottom part of the code above it works fine.  I’m using cocos2d-x V3.6 and a windows phone.

  • Sonar Systems admin
    Likes 0

    does it work then?

  • EnesOzdemir
    Likes 0

    it sort of works when I get rid of the collision detection, the bodies end up picking up a lot of speed and eventually break free from the boundary that I created.  Is there any resources or anything that may be able to assist me?

     

  • Sonar Systems admin
    Likes 0

    Unfortunately no, only the GitHub link we provided sorry

Login to reply