JSFiddle - React, Tailwind, and code Playground
by XTREME104
HTML
<!DOCTYPE html>
<html>
<body onload="init()" onmousemove="mouseMove(event)">
<canvas id="canvas"></canvas>
</body>
</html>
CSS
html, body {
margin: 0;
padding: 0;
overflow: hidden;
}
JavaScript
var mouseX = 0.0, mouseY = 0.0;
function Ball () {
this.x = 0.5;
this.y = 0.5;
this.velocityX = 0.5;
this.velocityY = Math.random() - 0.5;
this.size = 10;
var self = this;
this.tick = function () {
self.x += self.velocityX / 60;
self.y += self.velocityY / 60;
if (self.x < 0.0 && self.velocityX < 0.0)
self.velocityX = -self.velocityX;
if (self.x > 1.0 && self.velocityX > 0.0)
self.velocityX = -self.velocityX;
if (self.y < 0.0 && self.velocityY < 0.0)
self.velocityY = -self.velocityY;
if (self.y > 1.0 && self.velocityY > 0.0)
self.velocityY = -self.velocityY;
};
}
function Player () {
this.y = 0.5;
this.height = 0.35;
this.points = 0;
}
var canvas, context, player = new Player(), enemy = new Player(), ball = new Ball();
function init () {
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
setInterval(tick, 1000 / 60);
setInterval(draw, 1000 / 30);
}
function tick () {
ball.tick();
player.y = mouseY;
enemy.y += Math.min(Math.max(ball.y - enemy.y, -0.0025), 0.0025);
if (ball.x < 0.08 && ball.x > 0.04)
if (enemy.y - 0.25/ 2 < ball.y && enemy.y + 0.25 / 2 > ball.y) {
if (ball.velocityX < 0.0)
ball.velocityX = -ball.velocityX;
} else {
player.points++;
ball = new Ball();
}
if (ball.x > 1 - 0.08 && ball.x < 1 - 0.04)
if (player.y - 0.25/ 2 < ball.y && player.y + 0.25/ 2 > ball.y) {
if (ball.velocityX > 0.0)
ball.velocityX = -ball.velocityX;
} else {
enemy.points++;
ball = new Ball();
}
}
function draw () {
var width = window.innerWidth;
var height = window.innerHeight;
if (canvas.width != width)
canvas.width = width;
if (canvas.height != height)
canvas.height = height;
context.clearRect(0, 0, width, height);
...