I'm making an pool game with cocos2dx.
First, i setup the edgeBox with this parameters PhysicsMaterial(1.0f, 1.0f, 0.8f)
And then these 2 balls PhysicsMaterial(1.0f, 1.0f, 0.5f)
On the update function, i want slow down balls time by time without gravity (like making ground friction) by adding
physicsBody->setLinearDamping(0.3);
On the update function, i set the minimum velocity, if the velocity of each ball reaches lower than 15, reset velocity to 0,0
auto MV = 15;
auto v1 = player1->getPhysicsBody()->getVelocity();
auto v2 = player2->getPhysicsBody()->getVelocity();
if (v1.x > MV || v1.x < -MV ||
v1.y > MV || v1.y < -MV) {
} else if(v1 != Vec2(0,0)) {
player1->getPhysicsBody()->setVelocity(Vec2(0,0));
CCLOG("sx 1 : %f %f",v1.x,v1.y);
}
if (v2.x > MV || v2.x < -MV ||
v2.y > MV || v2.y < -MV) {
} else if(v2 != Vec2(0,0)) {
player2->getPhysicsBody()->setVelocity(Vec2(0,0));
CCLOG("sx 2 : %f %f",v2.x,v2.y);
}
Everything works fine except when the balls stand next to the wall or each other. I see the small blue glue to these objects, this is when the contact has been made.
And in these situation, i can't set the velocity to 0,0. I think there is some kind of force constantly changing the velocity. You can see the image below to see the blue glue and keep setting velocity = 0.0 like forever.
Firstly reset forces before setting velocity to zero: player2->getPhysicsBody()->resetForces();
Also gravity can be a cause that bodies continue to move. So you can set gravity to zero for whole physics world. For example:
auto scene = Scene::createWithPhysics();
scene->getPhysicsWorld()->setGravity(Vec2(0, 0));
or just for one particular body:
player2->getPhysicsBody()->setGravityEnable(false);
or you can customize velocity function:
#include "chipmunk.h"
cocos2d::PhysicsBody * pBody = player2->getPhysicsBody();
pBody->getCPBody()->velocity_func = customVelFunc;
where customVelFunc
could be defined as:
void customVelFunc(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
{
cpBodyUpdateVelocity(body, cpvzero, damping, dt);
}