基本对象运动
After adding an object to UNIGINE, you can control its transformations with your control devices. This article shows how to control basic object movements and combine different transformations.将对象添加到UNIGINE后,您可以使用控制设备控制其转换。 本文展示了如何控制基本的对象运动并组合不同的变换。
See Also请参阅#
Direction Vector方向向量#
The direction vector is an important concept of mesh transformation. To move the node forward, you should know where the forward direction of the mesh is. When the mesh is exported from a 3D editor, it saves the information about the forward direction. And when you add the mesh to UNIGINE, it has the same orientation it had in a 3D editor. 方向向量是网格变换的一个重要概念。 要向前移动节点,您应该知道网格的前进方向在哪里。 当网格从3D编辑器导出时,它会保存有关前进方向的信息。 当您将网格添加到UNIGINE时,它具有与3D编辑器中相同的方向。
A mesh in MayaMaya中的网格
|
The same mesh in UNIGINEUNIGINE中的相同网格
|
In the images above, the direction vector has the positive Y direction. To move this mesh forward, you should get the direction of the mesh by using the Y component (the second column) of the world transformation matrix of the mesh.在上面的图像中,方向矢量具有正Y方向。 要向前移动此网格,您应该通过使用网格的世界变换矩阵的Y组件(第二列)来获取网格的方向。
The point is that content creators and programmers should make an arrangement for the direction vector.重点是内容创建者和程序员应该为方向向量做出安排。
Basic Movements基本动作#
Prearrangement先期准备#
We are going to make a component that allows moving and rotating an object. To make the explanation unobstructed, we give supplementary parts of code and additional links here. The complete code is provided at the bottom of this article.我们将制作一个允许移动和旋转对象的组件。 为了使解释无障碍,我们在此处提供补充部分代码和附加链接。 本文底部提供了完整的代码。
To use the component system, we need to initialize it. This is done in AppSystemLogic.cpp as follows:要使用组件系统,我们需要初始化它。 这是在AppSystemLogic.cpp中完成的,如下所示:
#include "AppSystemLogic.h"
int AppSystemLogic::init()
{
Unigine::ComponentSystem::get()->initialize();
return 1;
}
We need the camera to observe the scene and an object that we are going to manipulate. We define these two nodes in AppWorldLogic.h and add all related logic in AppWorldLogic.cpp:我们需要摄像头来观察场景和我们要操纵的对象。 我们在AppWorldLogic.h中定义这两个节点,并在AppWorldLogic.cpp中添加所有相关逻辑:
#include <UnigineLogic.h>
#include <UnigineStreams.h>
#include <UnigineObjects.h>
#include <UniginePlayers.h>
using namespace Unigine;
class AppWorldLogic : public Unigine::WorldLogic
{
public:
AppWorldLogic();
virtual ~AppWorldLogic();
int init() override;
int update() override;
int postUpdate() override;
int updatePhysics() override;
int shutdown() override;
int save(const Unigine::StreamPtr &stream) override;
int restore(const Unigine::StreamPtr &stream) override;
private:
// define the ObjectMeshStatic instance
// so that it will be deleted with the AppWorldLogic instance
Unigine::ObjectMeshStaticPtr mesh;
//define the player camera
Unigine::PlayerPtr player;
};
#include "AppWorldLogic.h"
#include <UnigineMathLib.h>
#include <UnigineGame.h>
#include <UnigineMesh.h>
using namespace Math;
AppWorldLogic::AppWorldLogic(){}
AppWorldLogic::~AppWorldLogic(){}
int AppWorldLogic::init()
{
// get the current game camera
player = Game::getPlayer();
// set the camera position and direction to look at the object
player->setPosition(Vec3(4.0f, -3.401f, 1.5f));
player->setDirection(vec3(0.0f, 1.0f, -0.4f), player->getUp());
// create the ObjectMeshStatic by using the new mesh
mesh = ObjectMeshStatic::create("core/meshes/box.mesh");
// set the mesh position
mesh->setPosition(Vec3(4.0f, 0.0f, 1.0f));
return 1;
}
Creating and Adding the Property创建和添加属性#
We are going to write the code that controls the object's movements as a separate component to make it reusable. Create a new C++ class (the header and *.cpp files) in the project. Let's name this component MovementControls. You can also check this article for more details about adding components.我们将编写控制对象运动的代码作为一个单独的组件,使其可重用。 在项目中创建一个新的C++类(头文件和*.cpp文件)。 让我们将此组件命名为MovementControls。 您还可以查看这篇文章了解有关添加组件的更多详细信息。
#pragma once
#include <UnigineComponentSystem.h>
#include <UnigineLogic.h>
#include <UnigineStreams.h>
class MovementControls : public Unigine::ComponentBase
{
public:
COMPONENT_DEFINE(MovementControls, Unigine::ComponentBase);
COMPONENT_INIT(init);
COMPONENT_UPDATE(update);
void init();
void update();
};
#include "MovementControls.h"
#include <UnigineControls.h>
#include <UnigineEditor.h>
#include <UnigineMathLib.h>
#include <UnigineGame.h>
#include <UnigineVisualizer.h>
REGISTER_COMPONENT(MovementControls);
using namespace Unigine;
using namespace Math;
void MovementControls::init() {
}
void MovementControls::update() {
}
And to assign this property to the mesh we want to move, we add the following line in the init() method in AppWorldLogic.cpp:为了将此属性分配给我们要移动的网格,我们在AppWorldLogic.cpp中的init()方法中添加以下行:
int AppWorldLogic::init()
{
/* ... */
// assign the movement controlling property to the mesh
mesh->addProperty("MovementControls");
return 1;
}
Moving Forward向前移动#
This section demonstrates how to set the forward movement of the mesh.本节演示如何设置网格的向前移动。
In this example, we use the "p" key pressing to move the mesh forward. The direction vector is visualized for clarity.在这个例子中,我们使用"p"键来向前移动网格。 为了清晰起见,方向矢量被可视化。
In MovementControls.h, we add the property parameters to access them via Editor and set their initial values:在MovementControls.h中,我们添加属性参数以通过编辑器访问它们并设置它们的初始值:
#pragma once
#include <UnigineComponentSystem.h>
#include <UnigineLogic.h>
#include <UnigineStreams.h>
class MovementControls : public Unigine::ComponentBase
{
public:
COMPONENT_DEFINE(MovementControls, Unigine::ComponentBase);
// define the property parameters that can be adjusted via the Editor as well
PROP_PARAM(Node, moving_node);
// define the movement speed
PROP_PARAM(Float, movement_speed, 5.0f);
COMPONENT_INIT(init);
COMPONENT_UPDATE(update);
void init();
void update();
};
In MovementControls.cpp, we add the movement-related logic:在MovementControls.cpp中,我们添加了与运动相关的逻辑:
#include "MovementControls.h"
#include <UnigineControls.h>
#include <UnigineEditor.h>
#include <UnigineMathLib.h>
#include <UnigineGame.h>
#include <UnigineVisualizer.h>
REGISTER_COMPONENT(MovementControls);
using namespace Unigine;
using namespace Math;
void MovementControls::init() {
// enable visualizer
Visualizer::setEnabled(1);
// check if the key is pressed and update the state of the specified control
ControlsApp::setStateKey(Controls::STATE_AUX_0, 'p');
}
void MovementControls::update() {
// get the frame duration
float ifps = Game::getIFps();
// get the current world transformation matrix of the node this property is assigned to
Mat4 transform = node->getWorldTransform();
// get the direction vector of the node from the second column of the transformation matrix
Vec3 direction = transform.getColumn3(1);
// render the direction vector for visual clarity
Visualizer::renderDirection(node->getWorldPosition(), vec3(direction), vec4(1.0f, 0.0f, 0.0f, 1.0f), 0.1f, 0);
// check if the control key is pressed
if (ControlsApp::getState(Controls::STATE_AUX_0)) {
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position to the node
node->setWorldPosition(node->getWorldPosition() + delta_movement);
}
}
设置网格位置的另一种方法
The new position can be also set by setting the WorldTransform variable. The following examples contain the code from the Update() function of the AppWorldLogic class. The part of controls initialization is the same for this method, the difference is in the Update() function only.新位置也可以通过设置WorldTransform变量来设置。 以下示例包含来自AppWorldLogic类的Update()函数的代码。 控件初始化的部分与此方法相同,区别仅在Update()函数中。
// check if the control key is pressed
if (ControlsApp::getState(Controls::STATE_AUX_0)) {
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position to the node
node->setWorldTransform(translate(delta_movement) * transform);
}
}
Or you can change the translation column of the world transformation matrix (see the Matrix Transformations article) to move the node:或者您可以更改世界变换矩阵的translation列(请参阅Matrix Transformations文章)以移动节点:
// check if the control key is pressed.
if (ControlsApp::getState(Controls::STATE_AUX_0)) {
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position
// here, you can also use transform.setColumn3(3, transform.getColumn3(3) + delta_movement);
transform.setColumn(3, transform.getColumn(3) + Vec4(delta_movement, 1.0f));
// set a new world transform matrix to the mesh
node->setWorldTransform(transform);
}
}
Rotation旋转#
This section contains implementation of the mesh rotation.本节包含网格旋转的实现。
You can rotate the mesh in two ways, by changing the transformation matrix represented by the WorldTransform variable (recommended way) or via the SetWorldRotation() function. The following example uses the second one:您可以通过两种方式旋转网格,通过更改由WorldTransform变量表示的变换矩阵(推荐方式)或通过SetWorldRotation()函数。 下面的示例使用第二个:
#pragma once
#include <UnigineComponentSystem.h>
#include <UnigineLogic.h>
#include <UnigineStreams.h>
class MovementControls : public Unigine::ComponentBase
{
public:
COMPONENT_DEFINE(MovementControls, Unigine::ComponentBase);
// define the property parameters that can be adjusted via the Editor as well
PROP_PARAM(Node, moving_node);
// define the rotation speed
PROP_PARAM(Float, rotation_speed, 30.0f);
COMPONENT_INIT(init);
COMPONENT_UPDATE(update);
void init();
void update();
};
#include "MovementControls.h"
#include <UnigineControls.h>
#include <UnigineEditor.h>
#include <UnigineMathLib.h>
#include <UnigineGame.h>
#include <UnigineVisualizer.h>
REGISTER_COMPONENT(MovementControls);
using namespace Unigine;
using namespace Math;
void MovementControls::init() {
// enable visualizer
Visualizer::setEnabled(1);
// check if the key is pressed and update the state of the specified control
ControlsApp::setStateKey(Controls::STATE_AUX_1, 'o');
}
void MovementControls::update() {
// get the frame duration
float ifps = Game::getIFps();
// check if the control key is pressed
if (ControlsApp::getState(Controls::STATE_AUX_1)) {
// set the node rotation along the Z axis assuming node's scale equal to 1
node->setWorldRotation(node->getWorldRotation() * quat(rotateZ(rotation_speed * ifps)), 1);
}
}
In the example above, the node is rotated to the left by pressing the "o" keyboard key.在上面的示例中,节点通过按下"o"键盘键向左旋转。
- It is recommended to set the second argument of the SetWorldRotation() function to 1 for all non-scaled nodes to improve performance and accuracy.建议将所有非缩放节点的SetWorldRotation()函数的第二个参数设置为1,以提高性能和准确性。
- Scaling of nodes should be avoided whenever possible, as it requires addidional calculations and may lead to error accumulation.应尽可能避免节点的缩放,因为它需要额外的计算,并可能导致错误累积。
To rotate the object by via the WorldTransform variable, you should replace the line containing the SetWorldRotation() function in the example above with the following one:要通过WorldTransform变量旋转对象,您应该将上面示例中包含SetWorldRotation()函数的行替换为以下行:
node->setWorldTransform(node->getWorldTransform() * Mat4(rotateZ(rotation_speed * ifps)));
This way is preferred, especially in case of complex transformations, as it allows composing the transformation matrix and setting it only once.这种方式是优选的,特别是在复杂变换的情况下,因为它允许组合变换矩阵并只设置一次。
Combining Movements结合运动#
Combining different movement controls is not more difficult than adding only one movement control.结合不同的移动控件并不比仅添加一个移动控件更困难。
The following code is an example that adds a mesh to the world and assigns a component on it that allows controlling its movements. You can rotate the mesh by using the "o", "[" keyboard keys and move forward by using the "p" key.下面的代码是一个示例,它向世界添加了一个网格,并在其上分配了一个允许控制其运动的组件。 您可以使用"o", "["键盘键旋转网格体,并使用"p"键向前移动。
#include "AppSystemLogic.h"
#include <UnigineComponentSystem.h>
using namespace Unigine;
AppSystemLogic::AppSystemLogic(){}
AppSystemLogic::~AppSystemLogic(){}
int AppSystemLogic::init()
{
Unigine::ComponentSystem::get()->initialize();
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// start of the main loop
////////////////////////////////////////////////////////////////////////////////
int AppSystemLogic::update()
{
// Write here code to be called before updating each render frame.
return 1;
}
int AppSystemLogic::postUpdate()
{
// Write here code to be called after updating each render frame.
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// end of the main loop
////////////////////////////////////////////////////////////////////////////////
int AppSystemLogic::shutdown()
{
// Write here code to be called on engine shutdown.
return 1;
}
#ifndef __APP_WORLD_LOGIC_H__
#define __APP_WORLD_LOGIC_H__
#include <UnigineLogic.h>
#include <UnigineStreams.h>
#include <UnigineObjects.h>
#include <UniginePlayers.h>
using namespace Unigine;
class AppWorldLogic : public Unigine::WorldLogic
{
public:
AppWorldLogic();
virtual ~AppWorldLogic();
int init() override;
int update() override;
int postUpdate() override;
int updatePhysics() override;
int shutdown() override;
int save(const Unigine::StreamPtr &stream) override;
int restore(const Unigine::StreamPtr &stream) override;
private:
// define the ObjectMeshStatic instance
// so that it will be deleted with the AppWorldLogic instance
Unigine::ObjectMeshStaticPtr mesh;
//define the player camera
Unigine::PlayerPtr player;
};
#endif // __APP_WORLD_LOGIC_H__
#include "AppWorldLogic.h"
#include <UnigineMathLib.h>
#include <UnigineGame.h>
#include <UnigineMesh.h>
using namespace Math;
AppWorldLogic::AppWorldLogic(){}
AppWorldLogic::~AppWorldLogic(){}
int AppWorldLogic::init()
{
// get the current game camera
player = Game::getPlayer();
// set the camera position and direction to look at the object
player->setPosition(Vec3(4.0f, -3.401f, 1.5f));
player->setDirection(vec3(0.0f, 1.0f, -0.4f), player->getUp());
// create the ObjectMeshStatic by using the new mesh
mesh = ObjectMeshStatic::create("core/meshes/box.mesh");
// set the mesh position
mesh->setPosition(Vec3(4.0f, 0.0f, 1.0f));
// assign the movement controlling property to the mesh
mesh->addProperty("MovementControls");
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// start of the main loop
////////////////////////////////////////////////////////////////////////////////
int AppWorldLogic::update()
{
// Write here code to be called before updating each render frame: specify all graphics-related functions you want to be called every frame while your application executes.
return 1;
}
int AppWorldLogic::postUpdate()
{
// The engine calls this function after updating each render frame: correct behavior after the state of the node has been updated.
return 1;
}
int AppWorldLogic::updatePhysics()
{
// Write here code to be called before updating each physics frame: control physics in your application and put non-rendering calculations.
// The engine calls updatePhysics() with the fixed rate (60 times per second by default) regardless of the FPS value.
// WARNING: do not create, delete or change transformations of nodes here, because rendering is already in progress.
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// end of the main loop
////////////////////////////////////////////////////////////////////////////////
int AppWorldLogic::shutdown()
{
// Write here code to be called on world shutdown: delete resources that were created during world script execution to avoid memory leaks.
return 1;
}
int AppWorldLogic::save(const Unigine::StreamPtr &stream)
{
// Write here code to be called when the world is saving its state (i.e. state_save is called): save custom user data to a file.
UNIGINE_UNUSED(stream);
return 1;
}
int AppWorldLogic::restore(const Unigine::StreamPtr &stream)
{
// Write here code to be called when the world is restoring its state (i.e. state_restore is called): restore custom user data to a file here.
UNIGINE_UNUSED(stream);
return 1;
}
#pragma once
#include <UnigineComponentSystem.h>
#include <UnigineLogic.h>
#include <UnigineStreams.h>
class MovementControls : public Unigine::ComponentBase
{
public:
COMPONENT_DEFINE(MovementControls, Unigine::ComponentBase);
// define the property parameters that can be adjusted via the Editor as well
PROP_PARAM(Node, moving_node);
// define the movement speed
PROP_PARAM(Float, movement_speed, 5.0f);
// define the rotation speed
PROP_PARAM(Float, rotation_speed, 30.0f);
COMPONENT_INIT(init);
COMPONENT_UPDATE(update);
void init();
void update();
};
#include "MovementControls.h"
#include <UnigineControls.h>
#include <UnigineEditor.h>
#include <UnigineMathLib.h>
#include <UnigineGame.h>
#include <UnigineVisualizer.h>
REGISTER_COMPONENT(MovementControls);
using namespace Unigine;
using namespace Math;
void MovementControls::init() {
// enable visualizer
Visualizer::setEnabled(1);
// check if the key is pressed and update the state of the specified control
// you can use both 'p', 'o', '[' or ASCII codes (112, 111, 113)
ControlsApp::setStateKey(Controls::STATE_AUX_0, 'p');
ControlsApp::setStateKey(Controls::STATE_AUX_1, 'o');
ControlsApp::setStateKey(Controls::STATE_AUX_2, '[');
}
void MovementControls::update() {
// get the frame duration
float ifps = Game::getIFps();
// get the current world transformation matrix of the node this property is assigned to
Mat4 transform = node->getWorldTransform();
// get the direction vector of the node from the second column of the transformation matrix
Vec3 direction = transform.getColumn3(1);
// initialize the update flag and declare rotation and movement
int update_transform = 0;
Mat4 rotation;
Vec3 delta_movement;
// render the direction vector for visual clarity
Visualizer::renderDirection(node->getWorldPosition(), vec3(direction), vec4(1.0f, 0.0f, 0.0f, 1.0f), 0.1f, 0);
// check if the control key for movement is pressed
if (ControlsApp::getState(Controls::STATE_AUX_0))
{
// calculate the delta of movement
delta_movement = direction * movement_speed * ifps;
update_transform = 1;
}
// check if the control key for left rotation is pressed
if (ControlsApp::getState(Controls::STATE_AUX_1))
{
// set the node left rotation along the Z axis
rotation.setRotateZ(rotation_speed * ifps);
update_transform = 1;
}
// check if the control key for right rotation is pressed
else if (ControlsApp::getState(Controls::STATE_AUX_2))
{
// set the node right rotation along the Z axis
rotation.setRotateZ(-rotation_speed * ifps);
update_transform = 1;
}
// update transformation if necessary
if (update_transform)
{
// combine transformations: movement + rotation
transform = transform * rotation;
transform.setColumn3(3, transform.getColumn3(3) + delta_movement);
// set the resulting transformation
node->setWorldTransform(transform);
}
}
void MovementControls::forward() {
// get the frame duration
float ifps = Game::getIFps();
// get the current world transformation matrix of the node this property is assigned to
Mat4 transform = node->getWorldTransform();
// get the direction vector of the node from the second column of the transformation matrix
Vec3 direction = transform.getColumn3(1);
// render the direction vector for visual clarity
Visualizer::renderDirection(node->getWorldPosition(), vec3(direction), vec4(1.0f, 0.0f, 0.0f, 1.0f), 0.1f, 0);
// check if the control key is pressed
if (ControlsApp::getState(Controls::STATE_AUX_0)) {
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position to the node
node->setWorldPosition(node->getWorldPosition() + delta_movement);
}
}
void MovementControls::position_var_1() {
// get the frame duration
float ifps = Game::getIFps();
// get the current world transformation matrix of the mesh
Mat4 transform = node->getWorldTransform();
Vec3 direction = transform.getColumn3(1);
// check if the control key is pressed
if (ControlsApp::getState(Controls::STATE_AUX_0)) {
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position to the node
node->setWorldTransform(translate(delta_movement) * transform);
}
}
void MovementControls::position_var_2() {
// get the frame duration
float ifps = Game::getIFps();
// get the current world transformation matrix of the mesh
Mat4 transform = node->getWorldTransform();
Vec3 direction = transform.getColumn3(1);
// check if the control key is pressed.
if (ControlsApp::getState(Controls::STATE_AUX_0)) {
// calculate the delta of movement
Vec3 delta_movement = direction * movement_speed * ifps;
// set a new position
// here, you can also use transform.setColumn3(3, transform.getColumn3(3) + delta_movement);
transform.setColumn(3, transform.getColumn(3) + Vec4(delta_movement, 1.0f));
// set a new world transform matrix to the mesh
node->setWorldTransform(transform);
}
}
void MovementControls::rotation_var_1() {
// get the frame duration
float ifps = Game::getIFps();
// check if the control key is pressed
if (ControlsApp::getState(Controls::STATE_AUX_1)) {
// set the node rotation along the Z axis assuming node's scale equal to 1
node->setWorldRotation(node->getWorldRotation() * quat(rotateZ(rotation_speed * ifps)), 1);
}
}
void MovementControls::rotation_var_2() {
// get the frame duration
float ifps = Game::getIFps();
// check if the control key is pressed
if (ControlsApp::getState(Controls::STATE_AUX_1)) {
// set the node rotation along the Z axis assuming node's scale equal to 1
node->setWorldTransform(node->getWorldTransform() * Mat4(rotateZ(rotation_speed * ifps)));
}
}