将随机 JSON 对传递到帧组件中



Edit 3:代码现在可以跨许多对象工作(感谢Noam),他还帮助使随机函数与它一起工作。一旦实现,我将更新问题中的代码。

编辑2:我已经接受了Almosnino@Noam答案,现在正在尝试将其应用于具有许多对象的数组(不成功)。这是混音链接。请帮忙!

编辑:我得到了一些反馈,并找到了这个页面,其中讨论了使用JSON.parse函数。我已经编辑了代码以反映新的更改,但我仍然无法弄清楚到底缺少什么。

原文:我认为之前的答案将有助于我尝试解析 json 文件并返回随机字符串及其相关对(例如 Title-Platform),但我无法让它工作。我的目标是在场景中将输出渲染为文本项。我真的很喜欢使用 A-frame,但很难找到在这方面可以帮助我的文档。我尝试使用以下修改后的脚本从 Json 文件中获取文本......

AFRAME.registerComponent('super', {  // Not working
schema: { 
Games: {type: 'array'}, 
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el; 
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];   
const el.setAttribute('super', {Games: hugeArray}); 
el.setAttribute('position', {x:-2, y:2, z:-3}); 
} 
});

触发器也在我的 html 中设置以呈现文本。我的代码正在通过 glitch.com 处理,任何帮助将不胜感激!

要加载 json,我认为您需要使用 XMLHttpRequest(正如 Diego 在注释中指出的那样),加载后,您可以通过 setAttribute 设置文本。

下面是一个关于故障的基本示例: https://glitch.com/edit/#!/a-frame-json-to-text

在 init 上,它会执行请求,然后在完成后,它将加载的 json 文本设置到实体上。

AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});

更新版本:https://glitch.com/edit/#!/peppermint-direction

AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + 'n' + randomGame.Developer + 'nn'
if (nextGame != null) {
gameInfo += nextGame.Title + 'n' + nextGame.Developer + 'n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"}); 
});
request.send( null );
}
});

最新更新