three.jsaframeaframe-networked

Trouble setting dynamic room name in network a-frame


I'm having two a-texts both directs to same html

<a-text navigate="url: http://../room.html" color="green" position="0 2 0" value="Room 1"></a-text>
<a-text navigate="url: http://../room.html" color="green" position="0 2 0" value="Room 2"></a-text>

navigate is a register component which helps to redirect to different url on clicking text entity

AFRAME.registerComponent("navigate-on-click", {
  schema: {
    url: { default: "" },
  },

  init: function () {
    var data = this.data;
    var el = this.el;

    el.addEventListener("click", function () {
      window.location.href = data.url;
      });
  },
});

but I want to use same html with different room name as room 1 and room 2 so user clicks on different texts enters different room with same html file

<a-scene
    networked-scene="
    room: room;
    debug: true;
    adapter: wseasyrtc;
    serverURL:http://....com/;
  "> 

here room name is hard coded as room but I want to make it dynamic


Solution

  • create a component for dynamic room like this

    AFRAME.registerComponent('dynamic-room', {
      init: function () {
        var el = this.el;
        var params = this.getUrlParams();
    
        if (!params.room) {
          window.alert('Please add a room name in the URL, eg. ?room=myroom');
        }
    
        var isMultiuser = params.hasOwnProperty('room');
        var webrtc = params.hasOwnProperty('webrtc');
        var adapter = webrtc ? 'easyrtc' : 'wseasyrtc';
        var voice = params.hasOwnProperty('voice');
        
        var networkedComp = {
          room: params.room,
          adapter: adapter,
          audio: voice
        };
        console.info('Init networked-aframe with settings:', networkedComp);
        el.setAttribute('networked-scene', networkedComp);
      },
    
      getUrlParams: function () {
        var match;
        var pl = /\+/g;  // Regex for replacing addition symbol with a space
        var search = /([^&=]+)=?([^&]*)/g;
        var decode = function (s) { return decodeURIComponent(s.replace(pl, ' ')); };
        var query = window.location.search.substring(1);
        var urlParams = {};
    
        match = search.exec(query);
        while (match) {
          urlParams[decode(match[1])] = decode(match[2]);
          match = search.exec(query);
        }
        return urlParams;
      }
    });
    

    and in a-scene add the component dynamic-room