forked from shama/letswritecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (64 loc) · 1.7 KB
/
Copy pathindex.js
File metadata and controls
73 lines (64 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function (stream) {
const signalhub = require('signalhub')
const createSwarm = require('webrtc-swarm')
const hub = signalhub('my-game', [
'http://localhost:8080'
])
const swarm = createSwarm(hub, {
stream: stream
})
const Player = require('./player.js')
const you = new Player()
you.addStream(stream)
const players = {}
swarm.on('connect', function (peer, id) {
if (!players[id]) {
players[id] = new Player()
peer.on('data', function (data) {
data = JSON.parse(data.toString())
players[id].update(data)
})
players[id].addStream(peer.stream)
}
})
swarm.on('disconnect', function (peer, id) {
if (players[id]) {
players[id].element.parentNode.removeChild(players[id].element)
delete players[id]
}
})
// hub.subscribe('update').on('data', function (data) {
// if (data.color === you.color) return
// if (!players[data.color]) {
// players[data.color] = new Player(data)
// }
// players[data.color].update(data)
// //console.log(data)
// })
setInterval(function () {
//hub.broadcast('update', window.location.hash)
you.update()
//hub.broadcast('update', you)
const youString = JSON.stringify(you)
swarm.peers.forEach(function (peer) {
peer.send(youString)
})
}, 100)
document.addEventListener('keypress', function (e) {
const speed = 16
switch (e.key) {
case 'a':
you.x -= speed
break
case 'd':
you.x += speed
break
case 'w':
you.y -= speed
break
case 's':
you.y += speed
break
}
}, false)
})