示例项目和用例 > 用例:扩展数字映射体验 > Digital Twin 201:通过应用程序参数进行配置 > 创建颜色配置
  
创建颜色配置
在最后一节中,您已了解如何使用 model 应用程序参数来更改体验中模型的配置。现在,您将创建作用类似的名为 color 的应用程序参数。但是,必须创建一些脚本来启用它。
在本节中,将创建包含 RGBA 颜色的对象以便从 Vuforia Studio 进行访问。从对象中提取的颜色将被发送到 setColor 函数。然后,setColor 函数会将模型的外观更改为 color 应用程序参数指定的任何颜色。
1. 单击 Home.js,然后输入以下内容:
//
// object to hold color possibilities
var colorPalette = {
'red' : 'rgba(255,0,0,1);',
'green' : 'rgba(0,255,0,1);',
'blue' : 'rgba(0,0,255,1);',
'yellow' : 'rgba(255,255,0,1);',
'purple' : 'rgba(255,0,255,1);',
'cyan' : 'rgba(0,255,255,1);',
'white' : 'rgba(245,245,245,1);',
'black' : 'rgba(10,10,10,1);'
}
colorPalette 对象将用于保存模型可配置的所有可能的颜色。此体验中已添加了基本颜色列表,但由于 Studio 可识别 RGBA 颜色代码,因此您可以向体验添加任何其他所需的颜色。
2. 接下来,您将创建 setColor 函数用于为四轴飞行器设置所需颜色的。如果在 color 应用程序参数中定义了颜色,则将激活 if 语句内的代码。
a. 根据在 color 应用程序参数中输入的值,将从 colorPalette 对象中选择 RGBA 值,并将其设置为名为 paintColor 的变量。
b. 如果输入的颜色在 colorPalette 中为有效值,则将触发 PTC Metadata API promise。为确定是否满足 promise,将创建一个名为 toPaint 的变量,该变量将成为一个 painted 属性值为 true 的部件的列表。然后,如果存在符合该条件的部件,则 TML 3D 呈现器会更改这些特定部件的颜色,使其符合 paintColor 中的值。
c. 如果 promise 被拒绝,则一条错误语句将被记录到控制台。
d. Home.js 中输入以下代码:
//
// function for setting the color based on the color app parameter
$scope.setColor = function (model) {

//
// if color is defined, set color
// check if there is a part that can have its color changed
if ($scope.app.params.color != undefined) {

var paintColor = colorPalette[$scope.app.params.color];
if (paintColor != undefined)
PTC.Metadata.fromId('quadcopter')
.then((metadata) => {
//
// create variable named toPaint to become an array of ID paths that fit the input text
// "like" will look for a partial text match to what is typed in. use 'same' to get an exact match
var toPaint = metadata.find('painted').like('true').getSelected();

//
// if statement for determining parts that have the painted attribute and setting their color using the tml 3d renderer
if (toPaint != undefined && toPaint.length > 0 ) {

toPaint.forEach(function(p) {

tml3dRenderer.setColor(model+ '-' +p,paintColor);

}) // for each end

} // if statement end

}) //.then end

//
// catch statement for if this operation fails
.catch((err) => { console.log("metadata extraction failed with reason : " + err) })

} // end of if statement for paintColor

} // end of setColor function
3. 现在,您已经创建了更改模型颜色的函数,但尚未调用它们。要在加载 Studio 后立即执行此函数,需要创建 modelLoaded 事件侦听器函数。如其名称所示,当模型由 Studio 加载时,将运行此函数的主体。在本例中,加载模型时,将对指定模型触发 setColor 函数,以根据配置设置其颜色。
//modelLoaded event listener triggers when the model has completed loading
$scope.$on('modelLoaded', function (event,model) {

//
// call setColor function to change the color of the model
$scope.setColor(model)

}) // modelloaded end
4. 这将完成本节所需的所有脚本。要测试您的代码,请输入您在 colorPalette 对象内创建的颜色之一,作为 color 应用程序参数的值。单击“预览”,查看模型颜色的更改方式。我们的示例使用了黄色。如果您看到模型的颜色变化,则您已成功完成本节!
* 
此方法适合小范围使用,如果有许多具有多个配置的模型,则此方法会因为可添加到 Vuforia Studio 的模型的限制而不起作用。继续本“数字映射”用例,了解如何使用标识解析服务和 ThingWorx 来创建可扩展的体验。
接下来,您将开始使用标识解析服务(IRS)