[physics] add pre/post callback in `update()` (#19118)

* add physics update pre/post callback

* update space

* run before simulation
This commit is contained in:
Arnold 2018-10-16 16:37:51 +08:00 committed by minggo
parent f3ef6b80de
commit b70a6a6def
2 changed files with 33 additions and 5 deletions

View File

@ -872,6 +872,9 @@ void PhysicsWorld::step(float delta)
void PhysicsWorld::update(float delta, bool userCall/* = false*/)
{
if(_preUpdateCallback) _preUpdateCallback(); //fix #11154
if(!_delayAddBodies.empty())
{
updateBodies();
@ -880,7 +883,7 @@ void PhysicsWorld::update(float delta, bool userCall/* = false*/)
{
updateBodies();
}
auto sceneToWorldTransform = _scene->getNodeToParentTransform();
beforeSimulation(_scene, sceneToWorldTransform, 1.f, 1.f, 0.f);
@ -888,12 +891,12 @@ void PhysicsWorld::update(float delta, bool userCall/* = false*/)
{
updateJoints();
}
if (delta < FLT_EPSILON)
{
return;
}
if (userCall)
{
#if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
@ -950,6 +953,8 @@ void PhysicsWorld::update(float delta, bool userCall/* = false*/)
// Update physics position, should loop as the same sequence as node tree.
// PhysicsWorld::afterSimulation() will depend on the sequence.
afterSimulation(_scene, sceneToWorldTransform, 0.f);
if(_postUpdateCallback) _postUpdateCallback(); //fix #11154
}
PhysicsWorld* PhysicsWorld::construct(Scene* scene)
@ -1033,6 +1038,16 @@ void PhysicsWorld::afterSimulation(Node *node, const Mat4& parentToWorldTransfor
afterSimulation(child, nodeToWorldTransform, nodeRotation);
}
void PhysicsWorld::setPostUpdateCallback(const std::function<void()> &callback)
{
_postUpdateCallback = callback;
}
void PhysicsWorld::setPreUpdateCallback(const std::function<void()> &callback)
{
_preUpdateCallback = callback;
}
NS_CC_END
#endif // CC_USE_PHYSICS

View File

@ -310,6 +310,16 @@ public:
*/
void setDebugDrawMask(int mask);
/**
* set the callback which invoked before update of each object in physics world.
*/
void setPreUpdateCallback(const std::function<void()> &callback);
/**
* set the callback which invoked after update of each object in physics world.
*/
void setPostUpdateCallback(const std::function<void()> &callback);
/**
* Get the debug draw mask.
*
@ -352,7 +362,7 @@ protected:
virtual void addShape(PhysicsShape* shape);
virtual void removeShape(PhysicsShape* shape);
virtual void update(float delta, bool userCall = false);
virtual void debugDraw();
virtual bool collisionBeginCallback(PhysicsContact& contact);
@ -367,7 +377,7 @@ protected:
virtual void removeBodyOrDelay(PhysicsBody* body);
virtual void updateBodies();
virtual void updateJoints();
protected:
Vec2 _gravity;
float _speed;
@ -394,6 +404,9 @@ protected:
std::vector<PhysicsJoint*> _delayAddJoints;
std::vector<PhysicsJoint*> _delayRemoveJoints;
std::function<void()> _preUpdateCallback;
std::function<void()> _postUpdateCallback;
protected:
PhysicsWorld();
virtual ~PhysicsWorld();