【问题标题】:Is there a way to send variables through RTC in JS?有没有办法通过 JS 中的 RTC 发送变量?
【发布时间】:2021-03-28 07:20:39
【问题描述】:

我正在开发一个制作three.js 多人游戏的项目。我完成了基础知识,我现在需要做的就是添加多人游戏部分。我发现有一种叫做 RTC 的东西我可以使用而无需复杂地制作服务器。我需要做的就是通过通道发送玩家位置的变量,以便随机玩家可以看到另一个玩家的角色。我有点挣扎,那么有没有人可以帮助我完成这个单独的代码?谢谢!我也在使用 JSFiddle。 https://jsfiddle.net/Plain_Gamer/cqvh78dr/22/

function startup() {
  connectButton = document.getElementById('connectButton');
  disconnectButton = document.getElementById('disconnectButton');
  sendButton = document.getElementById('sendButton');
  messageInputBox = document.getElementById('message');
  receiveBox = document.getElementById('receivebox');

  connectButton.addEventListener('click', connectPeers, false);
  disconnectButton.addEventListener('click', disconnectPeers, false);
  sendButton.addEventListener('click', sendMessage, false);
}

localConnection = new RTCPeerConnection();

sendChannel = localConnection.createDataChannel(prompt('Create channel name...'));
remoteConnection = new RTCPeerConnection(prompt('Enter channel name...'));
remoteConnection.ondatachannel = RTCRtpReceiver;
<button id="connectButton" name="connectButton" class="buttonleft">
  Connect
</button>
<button id="disconnectButton" name="disconnectButton" class="buttonright" disabled>
  Disconnect
</button>
<div class="messagebox">
  <label for="message">Enter a message:
    <input type="text" name="message" id="message" placeholder="Message text" inputmode="latin" size=60 maxlength=120 disabled>
  </label>
  <button id="sendButton" name="sendButton" class="buttonright" disabled>
    Send
  </button>
</div>
<div class="messagebox" id="receivebox">
  <p>Messages received:</p>
</div>

【问题讨论】:

    标签: javascript html variables jsfiddle channel


    【解决方案1】:

    虽然我绝不是 WebRTC 专家,但我知道它可以发送字符串(请参阅 MDN)。我认为实现目标的最佳方法是将变量转换为对象,并将对象转换为可以发送的字符串。然后,在另一端,您可以解码字符串并获取数据。这是一个演示(没有 WebRTC)。

    let x = 0;
    let y = 0;
    
    // Convert variables x and y into an object
    let obj = { x, y };
    
    // Turn the object to a string
    let str = JSON.stringify(obj);
    console.log(str):
    
    // Turn the string back into the object
    let decodedObj = JSON.parse(str);
    console.log(decodedObj);

    【讨论】:

    • 我认为这可能会起作用,因为您无法通过 RTC 通道发送文字变量,您可能能够发送字符串和对象。非常感谢,这很有帮助。
    • 您可以发送一个字符串——请参阅我添加到答案中的链接。
    • 我因为提出一个说牛等的问题而被禁止。这是关于询问如何克隆 div 以将其用作 am mo。所以我会改变这个问题,你能查看新的问题吗? stackoverflow.com/questions/65345449/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多