添加新的可交互对象
Let's add a new type of interactable object that we can grab, hold, and throw (it will be inherited from the VRInteractable component) with an additional feature: some visual effect (for example, smoke) will appear when we grab the object and, it will disappear when we release the object.让我们添加一种新的可交互对象类型,我们可以抓取、持有和投掷它(它将继承自 VRInteractable 组件),并具有一个附加功能:当我们抓住该对象时会出现某种视觉效果(例如烟雾),当我们释放对象时该效果将消失。
-
Create a new VRObjectVFX component and add the following code to it:创建一个新的 VRObjectVFX 组件,并向其中添加以下代码:
源代码 (C++)#pragma once #include <UnigineComponentSystem.h> #include <UnigineLog.h> #include "../Framework/Components/VRInteractable.h" class VRObjectVFX : public VRInteractable { public: COMPONENT(VRObjectVFX, VRInteractable); COMPONENT_INIT(init); COMPONENT_UPDATE(update,); // 属性名称 PROP_NAME("VRObjectVFX"); // 包含特效的 *.node 资源 PROP_PARAM(File, vfx_asset); // 交互方法 void grabIt(VRPlayer* player, int hand_num) override; void throwIt(VRPlayer* player, int hand_num) override; protected: void init(); void update(); private: // 内部“抓取”状态 bool grabbed = false; // 从指定资源创建的 vfx 节点 Unigine::NodePtr vfx; };
源代码 (C++)#include "VRObjectVFX.h" using namespace Unigine; REGISTER_COMPONENT(VRObjectVFX); void VRObjectVFX::init() { // 检查是否指定了视觉特效资源 if (vfx_asset.nullCheck()) { Log::error("Node %s (VRObjectVFX) 错误:未指定 'vfx_asset'。\n", node->getName()); ComponentSystem::get()->removeComponent<VRObjectVFX>(node); return; } else { // 如果指定了,就从 *.node 资源创建新节点 vfx = NodeReference::create(FileSystem::guidToPath(FileSystem::getGUID(vfx_asset.getRaw()))); // 并隐藏该节点(特效) vfx->setEnabled(false); } } // 每帧为可交互对象调用该方法 void VRObjectVFX::update() { // 如果对象被抓取,更新特效的位置变换 if(grabbed) vfx->setWorldTransform(node->getWorldTransform()); } // 抓取节点时调用的方法 void VRObjectVFX::grabIt(VRPlayer* player, int hand_num) { // 设置当前对象状态为 'GRABBED' grabbed = true; // 显示特效 vfx->setEnabled(true); } // 释放节点时调用的方法 void VRObjectVFX::throwIt(VRPlayer* player, int hand_num) { // 取消 'GRABBED' 状态 grabbed = false; // 隐藏特效 vfx->setEnabled(false); }
-
Select the cylinder (NodeReference) node and click Edit to modify its contents. Add the VRObjectVFX property to the cylinder(ObjectMeshStatic) node.选择 cylinder(NodeReference) 节点并点击 Edit 以修改其内容。在 cylinder(ObjectMeshStatic) 节点上添加 VRObjectVFX 属性。
-
Drag the vr/particles/smoke.node asset to the Vfx Node field. This node stores the particle system representing the smoke effect. It is available in the vr/particles folder of the UNIGINE Starter Course Projects add-on.将 vr/particles/smoke.node 资源拖到 Vfx Node 字段中。此节点包含表示烟雾效果的粒子系统,它位于 vr/particles 文件夹中,属于 UNIGINE Starter Course Projects 附加内容。
-
Select the cylinder (NodeReference) node again and click Apply to save your changes to the NodeReference. 再次选择 cylinder(NodeReference) 节点并点击 Apply 以将更改保存到 NodeReference。
Save changes (Ctrl+S) and run the application via SDK Browser.保存更改(Ctrl+S)并通过 SDK Browser 运行应用程序。
Now, if you grab and hold the cylinder, it will generate smoke:现在,当你抓住并保持 cylinder 时,它会产生烟雾效果:
本页面上的信息适用于 UNIGINE 2.20 SDK.