2

我在从 JSON 文件中读取数据时遇到问题。我已经阅读了有关 Stack Overflow 和 JSON 文档的其他阅读 JSON 问题,但无济于事。

我正在尝试读取要在 Three.js 中显示的数据。以下代码段有效:

var obj = { "points" : [
{ "vertex":[0.0,0.0,0.0] },
{ "vertex":[200.0,0.0,0.0] },
{ "vertex":[-200.0,0.0,0.0] },
{ "vertex":[0.0,100.0,0.0] },
{ "vertex":[0.0,-100.0,0.0] },
{ "vertex":[0.0,0.0,300.0] },
{ "vertex":[0.0,0.0,-300.0] },
{ "vertex":[75.0,75.0,75.0] },
{ "vertex":[50.0,50.0,50.0] },
{ "vertex":[25.0,25.0,25.0] } ]};

var geometry = new THREE.Geometry();

for (var i=0;i<10;i++)
{
    var vertex = new THREE.Vector3();
    vertex.x = obj.points[i].vertex[0];
    vertex.y = obj.points[i].vertex[1];
    vertex.z = obj.points[i].vertex[2];
    geometry.vertices.push( vertex );
}

它读取点,然后将点渲染到更远的位置。我在 index.html 旁边有一个名为

测试.json

它包含以下内容:

{ "points" : [
{ "vertex":[0.0,0.0,0.0] },
{ "vertex":[200.0,0.0,0.0] },
{ "vertex":[-200.0,0.0,0.0] },
{ "vertex":[0.0,100.0,0.0] },
{ "vertex":[0.0,-100.0,0.0] },
{ "vertex":[0.0,0.0,300.0] },
{ "vertex":[0.0,0.0,-300.0] },
{ "vertex":[75.0,75.0,75.0] },
{ "vertex":[50.0,50.0,50.0] },
{ "vertex":[25.0,25.0,25.0] } 
]}

我的问题是以下不起作用(即不显示点):

var geometry = new THREE.Geometry();

var obj2 = jQuery.getJSON('test.json');

for (var i=0;i<10;i++)
{
    var vertex = new THREE.Vector3();
    vertex.x = obj2.points[i].vertex[0];
    vertex.y = obj2.points[i].vertex[1];
    vertex.z = obj2.points[i].vertex[2];
    geometry.vertices.push( vertex );
}

这些文件位于我的保管箱的公共文件夹中,并且可以从公共链接查看,即使如此,以防我使用 --allow-files-access-from-files 标志运行 chrome。

更新

我的主要错误是没有处理 getJSON 函数回调中的顶点。我的第二个错误是假设在回调中将顶点添加到几何堆栈就足够了。事实上,我必须从几何体创建对象并将其添加到场景中才能工作。非常感谢大家的帮助。

$.getJSON('test.json', function(obj2) {

    var geometry = new THREE.Geometry();

    for (var i=0;i<10;i++)
    {
        var vertex = new THREE.Vector3();
        vertex.x = obj2.points[i].vertex[0];
        vertex.y = obj2.points[i].vertex[1];
        vertex.z = obj2.points[i].vertex[2];
        geometry.vertices.push( vertex );
    }

    vc1 = geometry.vertices.length;

    object = new THREE.ParticleSystem( geometry, shaderMaterial );
    object.dynamic = true;

    var vertices = object.geometry.vertices;
    var values_size = attributes.size.value;
    var values_color = attributes.ca.value;

    for( var v = 0; v < vertices.length; v ++ ) {
    values_size[ v ] = 50;
    values_color[ v ] = new THREE.Color( 0xffffff );
    }

    scene.add( object );
});
4

3 回答 3

5

阅读getJSON的文档,这是一个异步调用!

您需要将 for 循环放入回调中。

于 2013-03-12T13:12:19.627 回答
1

我认为你应该这样做

$.getJSON('test.json', function(obj2) {
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = obj2.points[i].vertex[0];
vertex.y = obj2.points[i].vertex[1];
vertex.z = obj2.points[i].vertex[2];
geometry.vertices.push( vertex );
}
});

Edit1 错字

于 2013-03-12T13:16:25.343 回答
0

似乎是小错误。您可以执行以下操作:

1)检查你的html页面中是否引用了test.json?

2) 使用 firebug (console tab) 准确检查 getJson 方法返回的内容

于 2013-03-12T13:34:35.110 回答