Force and impulse Functions not working on rigidbody

I want to simply hit like ping pong game. I have attached a rigidbody with the ball and rod. I want to apply force upwards to ball on contact.

my code: I attached code to the rod

onBeginContact: function(contact, selfCollider, otherCollider) {
    console.log("Currently colliding with " + otherCollider.node.name);
    if (otherCollider.node.name == "ball") {

        var force = 200;

        this.ballNodeRigidBody.applyAngularImpulse(force);
    }

},

make sure object’s density is atleast 1

1 Like

okay i check it

1 Like

no it is not working

did you test if contact listener works with console log?

yes. log come here

try this

this.ball.node.getComponent(cc.RigidBody).applyAngularImpulse(force);

instead

this.ballNodeRigidBody.applyAngularImpulse(force);

1 Like

hm okay i trying this

you have to enable the physics system

https://docs.cocos.com/creator/manual/en/physics/physics/physics-manager.html

2 Likes

okay i update you thanks

this.getComponent(cc.RigidBody).applyForceToCenter(new cc.Vec2(0, 100000), false);

above works for me now on button click. but not in onBeginContact(contact, self, other) function. Can anyone tell the reason :slight_smile:

i can’t think of anything other than contact listener might be not working put a console log in place of this code this.getComponent(cc.RigidBody).applyForceToCenter(new cc.Vec2(0, 100000), false); and if it doesn’t work let me know

1 Like

yes it is coming with log. But onclick works better not the contact one

full code

cc.Class({
extends: cc.Component,

properties: {

},


onLoad: function() {


    cc.director.getPhysicsManager().enabled = true;



},

onEnable: function() {

},
onBeginContact(contact, self, other) {
    this.getComponent(cc.AudioSource).play();
    if (other.node.name == "bat") {
        console.log("In Currently colliding with " + other.node.name);


        console.log("----");
        this.getComponent(cc.RigidBody).applyForceToCenter(new cc.Vec2(0, 1000000), false);
        console.log("++++");


    }
}

,
onclick() {
    // working
    this.getComponent(cc.RigidBody).applyForceToCenter(new cc.Vec2(0, 1000000), false);

}

});

1 Like

replace this with this

self.applyForceToCenter(new cc.Vec2(0, 1000000), false);

1 Like

did it work? lemme know

1 Like

no
it is not.
But when i run in update method it is working now.

hmm weird Contact listener works and applying force works by itself but not inside contact listener function i think you are missing something but i don’t know good luck maybe try making a new post with more details

1 Like