How to Immediately stop when collision contact

How to Immediately stop when collision contact
0

#1

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!


#2

Have you set masks? example:

getPhysicsBody()->setCategoryBitmask(0x02);
getPhysicsBody()->setContactTestBitmask(UINT_MAX);

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!


#3

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

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

auto physicbody = PhysicsBody::createBox(Size(visibleSize.width, 200), PhysicsMaterial(0, 0, 0), Vec2(0, -280));
physicbody->setDynamic(false);
physicbody->setCategoryBitmask(1);
physicbody->setCollisionBitmask(1);
physicbody->setContactTestBitmask(1);
bg->addComponent(physicbody);

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.


#4

Why are your masks all the same?


#5

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


#6

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

Does anyone have anyidea or advise, please?