How to Immediately stop when collision contact

How to Immediately stop when collision contact


Hi everyone,

I have a problem, when my character move to a wall, he stucks inside the wall then bounce back like this:
image image
But I want it stop immediately right before the wall.
I added physics body to them, set PhysicsMaterial(0, 0, 0) and try moving the character by setPosition or setVelocity but not work…
Please help me!


Have you set masks? example:


Have you made a contact event?

// physics event
auto contactListener = cocos2d::EventListenerPhysicsContact::create();
contactListener->onContactBegin = std::bind(&PurpleKernel::onContactBegin, this, std::placeholders::_1);
    cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);

Do you define gravity, etc

Show us the code so we can help!


Thank for your attention!
I define a “ground”:

auto bg = Sprite::create("bg.png");
bg->setPosition(visibleSize.width / 2, visibleSize.height / 2);

auto physicbody = PhysicsBody::createBox(Size(visibleSize.width, 200), PhysicsMaterial(0, 0, 0), Vec2(0, -280));

Then a character:

auto character = Sprite::create("anim.png", Rect(0, 95, 32, 40));
character ->setPosition(getRand(50, visibleSize.width - 50), visibleSize.height / 2 + getRand(0, 200));
this->addChild(character );

auto physbody = PhysicsBody::createBox(Size(32, 40), PhysicsMaterial(100, 0, 0), Vec2(0, 0));
physbody ->setCategoryBitmask(1);
physbody ->setCollisionBitmask(1);
physbody ->setContactTestBitmask(1);
character ->addComponent(physbody);

Then a event:

auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_1(HelloWorld::onContactBegin, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);

When character fall down, it was like image at first post.


Why are your masks all the same?


I try setting Category and Collision for blocking each other, and ContactTest for detect contact with EventListenerPhysicsContact. Is anything wrong?


I tried remove all mask or adjust different value but still not work.

Does anyone have anyidea or advise, please?