xxxxxxxxxx
84
/*
This sketch uses p5LiveMedia to share video and data
*/
let myVideo;
let friends = {};
let myName = "";
let peer;
let myPosition = {
x: 10,
y: 10
}
function setup() {
createCanvas(windowWidth, windowHeight);
myVideo = createCapture(VIDEO,
function(stream) {
peer = new p5LiveMedia(this, "CAPTURE", stream, "friendTown")
peer.on('stream', gotStream);
// set up a data channel:
peer.on('data', gotData);
}
);
myVideo.muted = true;
myVideo.hide();
}
function draw() {
background(220, 100, 250);
image(myVideo, myPosition.x,myPosition.y, 160,120);
// this is one way of iterating over an object
for (const id in friends){
friends[id].display();
}
}
// We got a new stream!
function gotStream(stream, id) {
friends[id] = new Friend (stream);
}
function gotData(data, id) {
console.log("Got data:",data,"from:",id);
// If it is JSON, parse it
let parsedData = JSON.parse(data);
if (friends[id]){
friends[id].x = parsedData.x;
friends[id].y = parsedData.y;
}
}
function mousePressed() {
myPosition = {
x: mouseX,
y: mouseY
}
// Have to send string
peer.send(JSON.stringify(myPosition));
}
class Friend {
constructor(stream, id) {
this.x = 0;
this.y = 0;
this.stream = stream;
}
display() {
image(this.stream, this.x, this.y, 160, 120);
}
}