チュートリアル — Webrtc
Tutorial: two players talk peer to peer
Step 1: add the extension
bin/jumphp composer <game> require jumphp/webrtc (or the IDE: Extensions > WebRTC > Add). The engine finds it by itself.
Step 2: a peer in your scene
public function __construct(private \JumPHP\WebRtc\WebRtc $webrtc) {}
public function enter(array $params = []): void
{
$this->peer = $this->webrtc->peer();
$this->chat = $this->peer->channel('chat');
$this->chat->on('message', fn (string $text) => $this->lines[] = $text);
}
Step 3: the signals
The two peers must exchange a few messages (offer, answer, ICE candidates) before they connect. With the multiplayer relay:
\JumPHP\WebRtc\Signaling::overNet($params['net'], $this->peer, $params['peer']);
if ($params['host']) {
$this->peer->offer();
}
Start the scene through LobbyScene ('next' => YourScene::class): it gives net, peer and host.
Step 4: talk
if ($this->actions()->isPressed('confirm') && $this->chat->isOpen()) {
$this->chat->send('HELLO');
}
The text goes straight to the other player (on the same network it never leaves it). Run two windows: bin/jumphp relay up, then
bin/jumphp run <game> twice, or two browsers on the built page.
Step 5: fast positions
$this->pos = $this->peer->channel('pos', ordered: false, retransmits: 0); // like UDP: a late position is never waited for
What you see: games/webrtc-demo (samples LoopbackSample and OnlineSample).