<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Air Hockey</title>
<style>
html, body {
margin: 0;
padding: 0;
background: #111;
overflow: hidden;
}
canvas {
display: block;
background: #000;
}
</style>
</head>
<body>
<canvas id="game"></canvas>
<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resize();
window.addEventListener("resize", resize);
// Objekte
const paddleRadius = 40;
const puckRadius = 20;
const paddle1 = { x: 0, y: 0 };
const paddle2 = { x: 0, y: 0 };
const puck = {
x: 0,
y: 0,
vx: 5,
vy: 6
};
function reset() {
paddle1.x = canvas.width / 2;
paddle1.y = canvas.height - 80;
paddle2.x = canvas.width / 2;
paddle2.y = 80;
puck.x = canvas.width / 2;
puck.y = canvas.height / 2;
}
reset();
// Input
function move(e) {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
const touch = e.touches ? e.touches[0] : e;
const x = touch.clientX - rect.left;
const y = touch.clientY - rect.top;
if (y > canvas.height / 2) {
paddle1.x = x;
paddle1.y = y;
} else {
paddle2.x = x;
paddle2.y = y;
}
}
canvas.addEventListener("mousemove", move);
canvas.addEventListener("touchmove", move, { passive: false });
// Physik
function collision(p) {
const dx = puck.x - p.x;
const dy = puck.y - p.y;
const dist = Math.hypot(dx, dy);
if (dist < puckRadius + paddleRadius) {
const angle = Math.atan2(dy, dx);
puck.vx = Math.cos(angle) * 8;
puck.vy = Math.sin(angle) * 8;
}
}
function update() {
puck.x += puck.vx;
puck.y += puck.vy;
if (puck.x < puckRadius || puck.x > canvas.width - puckRadius)
puck.vx *= -1;
if (puck.y < puckRadius || puck.y > canvas.height - puckRadius)
puck.vy *= -1;
collision(paddle1);
collision(paddle2);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "#555";
ctx.setLineDash([10, 10]);
ctx.beginPath();
ctx.moveTo(0, canvas.height / 2);
ctx.lineTo(canvas.width, canvas.height / 2);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(puck.x, puck.y, puckRadius, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "dodgerblue";
ctx.beginPath();
ctx.arc(paddle1.x, paddle1.y, paddleRadius, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(paddle2.x, paddle2.y, paddleRadius, 0, Math.PI * 2);
ctx.fill();
}
function loop() {
update();
draw();
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>