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);
}
},
Musab
December 24, 2018, 11:57am
2
make sure object’s density is atleast 1
1 Like
Musab
December 24, 2018, 12:09pm
5
did you test if contact listener works with console log?
Musab
December 24, 2018, 12:20pm
7
try this
this.ball.node.getComponent(cc.RigidBody).applyAngularImpulse(force);
instead
this.ballNodeRigidBody.applyAngularImpulse(force);
1 Like
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
Musab
December 24, 2018, 4:29pm
12
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
Musab
December 24, 2018, 6:42pm
14
replace this with this
self.applyForceToCenter(new cc.Vec2(0, 1000000), false);
1 Like
no
it is not.
But when i run in update method it is working now.
Musab
December 26, 2018, 10:11am
17
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