NPC FOLLOW PLAYER SOLUTION HERE!!!

majc

19-08-2008 01:13:48

Ok finaly i got my NPC working only with physics after all it wasnt impossible lol
This is the code:

void cNPCcollisionHandler::updateMovement(Body *body)
{
Ogre::Vector3 Destination, Position;
Ogre::Quaternion npcOrientation;
Ogre::Quaternion playerOrientation;
mPlayer->getBody()->getPositionOrientation(Destination,playerOrientation);
body->getPositionOrientation(Position,npcOrientation);
Ogre::Vector3 goalHeading = Destination - Position;
goalHeading.y = 0.0f;
goalHeading.normalise();
Ogre::Vector3 curHeading = npcOrientation * Ogre::Vector3::UNIT_X;
Ogre::Degree delta_o = Math::ACos( curHeading.dotProduct( goalHeading ) );
Ogre::Vector3 rot_axis = curHeading.crossProduct( goalHeading ).normalisedCopy();
body->addLocalForce(gravity * mNPC->getMass(), Ogre::Vector3::ZERO);
body->addTorque( (rot_axis * delta_o.valueDegrees() * 400.0f) - (body->getOmega()* 1000.0f) );
body->setVelocity(npcOrientation * Ogre::Vector3::UNIT_X * 100);
}

void cNPCcollisionHandler::faceToEnemy(Body *body)
{

body->setCustomForceAndTorqueCallback <cNPCcollisionHandler>(&cNPCcollisionHandler::updateMovement,this);
}


Change the values 400.0f and 1000.0f in the following line with your own values, these worked for me because of my NPC mass, you have to try you own values.

body->addTorque( (rot_axis * delta_o.valueDegrees() * 400.0f) - (body->getOmega()* 1000.0f) );


The faceToEnemy function is called in the framelister.
I hope this post help other ppl.
Alot of thanks to wallaber that helped me with the solution.