【问题标题】:Threejs Particle System with joining lines. Programming logic?带有连接线的 Threejs 粒子系统。编程逻辑?
【发布时间】:2017-09-27 02:27:47
【问题描述】:

基于我最近发布的上一个问题: How to create lines between nearby particles in ThreeJS?

我能够创建连接附近粒子的单独线条。然而,由于粒子系统的逻辑,线条被绘制了两次。这是因为原始 2D 粒子系统的工作方式: https://awingit.github.io/particles/

这也会画线两次。对于连接一条线的每一对粒子,绘制一条线。

我认为这对于性能来说并不理想。我如何只为每个连接点画一条线?

附:这正是我想要达到的效果,但无法理解代码: http://freelance-html-developer.com/clock/

我想了解基本逻辑。

更新:

我已经创建了一个jsfiddle 来记录我的进度。

    var canvas, canvasDom, ctx, scene, renderer, camera, controls, geocoder, deviceOrientation = false;
    var width = 800,
        height = 600;
    var particleCount = 20;


    var pMaterial = new THREE.PointsMaterial({
        color: 0x000000,
        size: 0.5,
        blending: THREE.AdditiveBlending,
        //depthTest: false,
        //transparent: true
    });
    var particles = new THREE.Geometry;
    var particleSystem;
    var line;
    var lines = {};
    var lineGroup = new THREE.Group();
    var lineMaterial = new THREE.LineBasicMaterial({
        color: 0x000000,
        linewidth: 1
    });

    var clock = new THREE.Clock();
    var maxDistance = 15;

    function init() {
        canvasDom = document.getElementById('canvas');
        setupStage();
        setupRenderer();
        setupCamera();
        setupControls();
        setupLights();
        clock.start();
        window.addEventListener('resize', onWindowResized, false);
        onWindowResized(null);
        createParticles();
        scene.add(lineGroup);
        animate();
    }

    function setupStage() {
        scene = new THREE.Scene();
    }

    function setupRenderer() {
        renderer = new THREE.WebGLRenderer({
            canvas: canvasDom,
            logarithmicDepthBuffer: true
        });
        renderer.setSize(width, height);
        renderer.setClearColor(0xfff6e6);
    }

    function setupCamera() {
        camera = new THREE.PerspectiveCamera(70, width / height, 1, 10000);
        camera.position.set(0, 0, -60);
    }

    function setupControls() {
        if (deviceOrientation) {
            controls = new THREE.DeviceOrientationControls(camera);
            controls.connect();
        } else {
            controls = new THREE.OrbitControls(camera, renderer.domElement);
            controls.target = new THREE.Vector3(0, 0, 0);
        }
    }

    function setupLights() {
        var light1 = new THREE.AmbientLight(0xffffff, 0.5); // soft white light
        var light2 = new THREE.PointLight(0xffffff, 1, 0);

        light2.position.set(100, 200, 100);

        scene.add(light1);
        scene.add(light2);
    }

    function animate() {
        requestAnimationFrame(animate);
        controls.update();
        animateParticles();
        updateLines();
        render();
    }

    function render() {
        renderer.render(scene, camera);
    }

    function onWindowResized(event) {
        width = window.innerWidth;
        height = window.innerHeight;
        camera.aspect = width / height;
        camera.updateProjectionMatrix();
        renderer.setSize(width, height);
    }

    function createParticles() {
        for (var i = 0; i < particleCount; i++) {
            var pX = Math.random() * 50 - 25,
                pY = Math.random() * 50 - 25,
                pZ = Math.random() * 50 - 25,
                particle = new THREE.Vector3(pX, pY, pZ);
            particle.diff = Math.random() + 0.2;
            particle.default = new THREE.Vector3(pX, pY, pZ);
            particle.offset = new THREE.Vector3(0, 0, 0);
            particle.velocity = {};
            particle.velocity.y = particle.diff * 0.5;
            particle.nodes = [];
            particles.vertices.push(particle);
        }
        particleSystem = new THREE.Points(particles, pMaterial);
        particleSystem.position.y = 0;
        scene.add(particleSystem);
    }

    function animateParticles() {
        var pCount = particleCount;
        while (pCount--) {
            var particle = particles.vertices[pCount];
            var move = Math.sin(clock.getElapsedTime() * (1 * particle.diff)) / 4;

            particle.offset.y += move * particle.velocity.y;
            particle.y = particle.default.y + particle.offset.y;

            detectCloseByPoints(particle);
        }
        particles.verticesNeedUpdate = true;
        particleSystem.rotation.y += 0.01;
        lineGroup.rotation.y += 0.01;
    }

    function updateLines() {
        for (var _lineKey in lines) {
            if (!lines.hasOwnProperty(_lineKey)) {
                continue;
            }
            lines[_lineKey].geometry.verticesNeedUpdate = true;
        }
    }

    function detectCloseByPoints(p) {
        var _pCount = particleCount;
        while (_pCount--) {
            var _particle = particles.vertices[_pCount];
            if (p !== _particle) {

                var _distance = p.distanceTo(_particle);
                var _connection = checkConnection(p, _particle);

                if (_distance < maxDistance) {
                    if (!_connection) {
                        createLine(p, _particle);
                    }
                } else if (_connection) {
                    removeLine(_connection);
                }
            }
        }
    }

    function checkConnection(p1, p2) {
        var _childNode, _parentNode;
        _childNode = p1.nodes[particles.vertices.indexOf(p2)] || p2.nodes[particles.vertices.indexOf(p1)];
        if (_childNode && _childNode !== undefined) {
            _parentNode = (_childNode == p1) ? p2 : p1;
        }
        if (_parentNode && _parentNode !== undefined) {
            return {
                parent: _parentNode,
                child: _childNode,
                lineId: particles.vertices.indexOf(_parentNode) + '-' + particles.vertices.indexOf(_childNode)
            };
        } else {
            return false;
        }
    }

    function removeLine(_connection) {
        // Could animate line out
        var childIndex = particles.vertices.indexOf(_connection.child);
        _connection.parent.nodes.splice(childIndex, 1);
        deleteLine(_connection.lineId);
    }

    function deleteLine(_id) {
        lineGroup.remove(lines[_id]);
        delete lines[_id];
    }

    function addLine(points) {
        var points = points || [new THREE.Vector3(Math.random() * 10, Math.random() * 10, Math.random() * 10), new THREE.Vector3(0, 0, 0)];
        var _lineId = particles.vertices.indexOf(points[0]) + '-' + particles.vertices.indexOf(points[1]);
        var lineGeom = new THREE.Geometry();
        if (!lines[_lineId]) {
            lineGeom.dynamic = true;
            lineGeom.vertices.push(points[0]);
            lineGeom.vertices.push(points[1]);
            var curLine = new THREE.Line(lineGeom, lineMaterial);
            curLine.touched = false;
            lines[_lineId] = curLine;
            lineGroup.add(curLine);
            return curLine;
        } else {
            return false;
        }
    }

    function createLine(p1, p2) {
        p1.nodes[particles.vertices.indexOf(p2)] = p2;
        addLine([p1, p2]);
    }

    $(document).ready(function() {
        init();
    });

我真的很接近,但我不确定它是否已优化。似乎有闪烁的线条,有时线条会卡在原地。

所以这是我的想法。我点击了,我所要做的就是使线条的 Vector3 点等于相关粒子 Vector3 点。我只需要更新每一行geometry.verticesNeedUpdate = true;

另外,我管理线条的方式是使用 2 个点的索引创建一个唯一 ID,例如行['8-2'] = 行

【问题讨论】:

  • 只是一个建议:当你连接节点时,为它所连接的所有其他节点的每个节点保留一个列表。然后,然后您到达问题的另一端(第二个连接),检查您尝试连接 to 的那个是否已经连接到您要连接 from。如果这没有意义,请告诉我,我会详细说明。
  • 谢谢@TheJim01,您能否详细说明一下。我认为您要解释的内容接近我的需要。我只需要了解管理节点和线路的逻辑。我考虑过单独的循环。这是我的挑战,我如何有效地跟踪连接 2 个点的线。我的想法是,当我遍历节点时,我检查哪些节点在附近,然后如果有一个节点足够接近,那么我添加/更新分配给两个节点的线。我不确定我是否走在正确的轨道上。
  • 是的,您正朝着正确的方向前进。但即使是我的建议也有点矫枉过正。请参阅下面的答案,以更简洁地检查您的观点。

标签: javascript three.js particle-system


【解决方案1】:

您实际上要解决的问题是,在循环遍历点列表时,成功匹配的次数增加了一倍。

示例:

考虑一个点列表,[A, B, C, D]。您的循环测试每个点与所有其他点。对于此示例,AC 是仅有的足够接近的点,可以考虑在附近。

在第一次迭代中,A vs. all,你发现AC 就在附近,所以你添加了一行。但是当您对C 进行迭代时,您还会发现A 就在附近。这会导致第二行,这是您要避免的。

修复它:

解决方案很简单:不要重新访问您已经检查过的节点。这是因为distance from A to C 的答案与distance from C to A 没有什么不同。

最好的方法是调整检查循环的索引:

// (Note: This is example code, and won't "just work.")
for(var check = 0, checkLength = nodes.length; check < checkLength; ++check){
    for(var against = check + 1, against < checkLength; ++against){
        if(nodes[check].distanceTo(nodes[against]) < delta){
            buildThatLine(nodes[check], nodes[against]);
        }
    }
}

在内部循环中,索引设置为:

  1. 跳过当前节点
  2. 跳过当前节点之前的所有节点。

这是通过将内部索引初始化为外部索引 + 1 来完成的。

警告:

此特定逻辑假定您丢弃每一帧的所有行。这不是实现效果的最有效方法,但我将把它作为一种练习留给你。

【讨论】:

  • 感谢@TheJim01 的反馈。我想我已经尝试过这种方法,但问题是每个粒子只能有一个连接而不是多个,我假设。此外,我希望控件在建立连接后为一条线设置动画,因此我需要对每条线本身进行更多控制。除此之外,我想我想要的是能够设置每个点可以有多少条线,以及每条线可以控制和动画。
  • 突然想到一个想法。也许我可以为每一帧清除线条并将线条属性存储在“父”节点上?因此,无论哪个点先画线,都将存储要绘制的线的样式和属性。您对此有何看法?
  • 1) 它应该将每个节点连接到符合标准的尽可能多的节点。画一条线不会跳过其余的节点。 :) 2) 当然,这听起来也不错。请记住,添加它们是成功的一半,当点相距太远时,您还需要删除它们。 :)
  • 所以我决定设置一个 jsfiddle 我到目前为止所做的事情。我真的很接近,但我不确定它是否优化了。似乎有闪烁的线条,有时线条会卡在原地:jsfiddle.net/awinhayden/387c3xa7/2 所以这是我的想法。我点击了我所要做的就是使线条的 Vector3 点等于相关的粒子 Vector3 点。我只需要更新每一行geometry.verticesNeedUpdate = true;哦,我如何管理线条是我使用 2 个点的索引创建一个唯一 ID,例如行['8-2'] = 行;
  • 我应该为此发布一个新问题吗?
猜你喜欢
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
  • 2012-06-28
  • 1970-01-01
  • 2011-04-14
相关资源
最近更新 更多