Pong

by Nathan Piper

HTML

<canvas id="background" width="500" height="500"></canvas>
<canvas id="player" width="500" height="500"></canvas>
<canvas id="enemy" width="500" height="500"></canvas>
<canvas id="ball" width="500" height="500"></canvas>
<canvas id="gui" width = "500" height="500"></canvas>

CSS

canvas {
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 500px;
    position: absolute;
    top: 0;
    left: 0;
}
#background{
  background: black;
}

JavaScript

var bg = document.getElementById('background').getContext('2d');
var pg = document.getElementById('player').getContext('2d');
var eg = document.getElementById('enemy').getContext('2d');
var cg = document.getElementById('ball').getContext('2d');
var gui = document.getElementById('gui').getContext('2d');

var width = 500;
var height = 500;
var fps = 60;

var playerPad = {
	x: 7,
  y: 250-25,
  width: 8,
  height: 80,
  speed: 5,
  score: 0,
  render: function(){
  	pg.fillStyle = 'white';
  	pg.fillRect(this.x, this.y, this.width, this.height);
  },
  tick: function(){
  	if (Key.up && this.y > 0) this.y -= this.speed;
    if (Key.down && this.y < height - 80) this.y += this.speed;
  }
}
var ball = {
	height: 8,
  width: 8,
  speed: 5,
  x: width/2,
  y: height/2,
  yIntersect: 0,
  maxAngle: 1,
  angle: 45,
  vx: 3,
  vy: 0,
  xDirection: Math.round(Math.random()),
  yDirection: 0,
  render: function(){
    cg.fillStyle = 'white';  
  	cg.fillRect(this.x, this.y, this.width, this.height);
  },
  reset: function(){
  	this.y = height/2;
    this.x = width/2;
    this.yIntersect = 0;
    this.angle = 45;
    this.vx = 3;
    this.vy = 0;
    this.xDirection = Math.round(Math.random());
    this.yDirection = 0;
  },
  tick: function(){
  	console.log(this.angle);
    if(collision(this,playerPad)){
      this.xDirection = 0;
    	this.yIntersect = (this.y - playerPad.y - playerPad.height/2)/40;
      this.angle = this.maxAngle*this.yIntersect;
      this.vx = Math.abs(Math.cos(this.angle))*this.speed;
      this.vy = Math.abs(Math.sin(this.angle))*this.speed;
      enemyPad.poi = this.vy * enemyPad.x-this.x
      if(this.angle <= 0){
				this.yDirection = 0;
      } else if(this.angle > 0){
				this.yDirection = 1;
      }
    }
    if(collision(this, enemyPad)){
    	this.xDirection = 1;
    	this.yIntersect = (this.y - enemyPad.y - enemyPad.height/2)/40;
      this.angle = this.maxAngle*this.yIntersect;
      this.vx = Math.abs(Math.cos(this.angle))*this.speed;
    ...