前几日写了一个小DEMO用到键盘用ASDW等按键控制一个物体的上下左右移动和旋转等操作。
这个是一个非常基础的简单控制,但是查询官方文档也是很吃力。
因此,分享在此处,方便大家不用闭门造车,重复造车。
使用注意:
1:移动旋转速度,自行控制
2:我的代码操作的是mSelectedNode,这个节点对象请自行准备。
代码运行版本Unigine2.5
但相信可以作用在几乎所有的Unigine版本中。因为都是基础操作函数。
int AppWorldLogic::update()
{
//设置旋转和移动的速度
Unigine::App* app = Unigine::App::get();
float movement_speed = 5.0;
float rotation_speed = 5.0f;
//有当前对象才操作
if (mSelectedNode)
{
Vec3 oldPos = mSelectedNode->getPosition();
// get the frame duration
float ifps = Game::get()->getIFps();
// get the current world transformation matrix of the mesh
Mat4 transform = mSelectedNode->getWorldTransform();
// get the direction vector of the mesh from the second column of the transformation matrix
//用aswd控制上下左右的位置变化,参考游戏控制
if (app->getKeyState('a') && !Console::get()->getActivity())
{
Vec3 direction = transform.getColumn3(0);
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position to the mesh
mSelectedNode->setWorldPosition(mSelectedNode->getWorldPosition() - delta_movement);
}
if (app->getKeyState('w') && !Console::get()->getActivity())
{
Vec3 direction = transform.getColumn3(1);
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position to the mesh
mSelectedNode->setWorldPosition(mSelectedNode->getWorldPosition() + delta_movement);
}
if (app->getKeyState('s') && !Console::get()->getActivity())
{
Vec3 direction = transform.getColumn3(1);
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position to the mesh
mSelectedNode->setWorldPosition(mSelectedNode->getWorldPosition() - delta_movement);
}
if (app->getKeyState('d') && !Console::get()->getActivity())
{
Vec3 direction = transform.getColumn3(0);
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position to the mesh
mSelectedNode->setWorldPosition(mSelectedNode->getWorldPosition() + delta_movement);
}
//用wr控制左侧旋转和右侧
if (app->getKeyState('q') && !Console::get()->getActivity())
{
// set the node rotation along the Z axis
mSelectedNode->setWorldRotation(mSelectedNode->getWorldRotation() * quat(rotateZ(rotation_speed * ifps)));
}
if (app->getKeyState('e') && !Console::get()->getActivity())
{
// set the node rotation along the Z axis
mSelectedNode->setWorldRotation(mSelectedNode->getWorldRotation() * quat(rotateZ(-rotation_speed * ifps)));
}
}
}