class Player {
constructor(x) {
this.x = x;
this.y = 400;
this.h = 90;
this.w = 15;
}
update_pos(y){
this.y = y;
}
draw(){
fill('#ffffff');
rect(this.x, this.y, this.w, this.h);
}
move(amount){
this.y += amount;
}
}
class Ball{
constructor(){
this.x = 400;
this.y = 400;
this.vel_x = 2;
this.vel_y = 5;
this.r = 10
}
update_pos(){
if (this.x < 10 || this.x > 800 - 10) {
this.vel_x *= -1;
}
if (this.y < 10 || this.y > 800 - 10) {
this.vel_y *= -1;
}
this.x += this.vel_x;
this.y += this.vel_y;
}
check_collision(player) {
// if ball collides on x-axis
if ((player.x - this.r) < this.x && this.x < (player.x + player.w + this.r)) {
// and on y-axis
if ((player.y - this.r) < this.y && this.y < (player.y + player.h + this.r)) {
this.vel_x *= -1
}
}
}
draw(){
fill(255);
ellipse(this.x, this.y, this.r * 2);
}
respawn() {
this.x = 400
this.y = 400
}
}
AB.socketStart();
// Canvas
function setup() {
createCanvas(800, 800);
left = new Player(30);
right = new Player(800 - 50);
ball = new Ball();
}
function draw() {
// Background
background(0);
if ( AB.socket ){
if ( AB.socket.connected ){
AB.socketOut([left.x, left.y, right.x, right.y, ball.x, ball.y, ball.vel_x, ball.vel_y]);
}
}
ball.draw();
left.draw();
right.draw();
ball.update_pos();
ball.check_collision(left);
ball.check_collision(right);
if (keyIsDown(87)) { // W
left.move(-10);
} else if (keyIsDown(83)) { // S
left.move(10);
}
if (keyIsDown(UP_ARROW)) {
right.move(-10);
} else if (keyIsDown(DOWN_ARROW)) {
right.move(10);
}
}
AB.socketIn = function(array) // incoming data on socket
{
left.x = array[0];
left.y = array[1];
right.x = array[2];
right.y = array[3];
ball.x = array[4];
ball.y = array[5];
ball.vel_x = array[6];
ball.vel_y = array[7];
};