作用:旋转角色朝向目标。
比如玩家靠近怪物。。怪物还没有朝向玩家,怪物发现了玩家,怪物转身朝向玩家并追赶。
以前用小画家画的草图。
模拟怪物旋转Y轴朝向角色
下面用irrlicht引擎做代码演示。
//朝向目标.只旋转y轴
core::vector3df faceTarget(IAnimatedMeshSceneNode* playerNode,irr::core::vector3df targetpos,f32 fixrot)
{
vector3df nodepos=playerNode->getPosition();
core::vector3df posDiff = targetpos - nodepos; //向量.角色->目标
f32 degree = nodepos.Y; //keep current rotation if nothing to do
posDiff.normalize();
//printf("dir %3.1f %3.1f %3.1f\n",posDiff.X,posDiff.Y,posDiff.Z);
if (posDiff.X != 0.0f || posDiff.Z != 0.0f)
degree = atan2(posDiff.X,posDiff.Z) * core::RADTODEG;
playerNode->setRotation( core::vector3df( 0,degree+fixrot,0) ); //有个模型修复角度
return core::vector3df(0,degree,0);
}
//完整的旋转朝向目标.xyz3轴都旋转了
core::vector3df faceTarget2(IAnimatedMeshSceneNode* playerNode,irr::core::vector3df targetpos,f32 fixrot)
{
// rotate to face target Node
vector3df nodePos = playerNode->getPosition();
vector3df diff = targetpos - nodePos; //求得朝向目标的向量
diff.normalize();
vector3df rot=diff.getHorizontalAngle();
rot.Y+=fixrot;
playerNode->setRotation( rot );
playerNode->updateAbsolutePosition();
rot.Y-=fixrot;
return rot;
}