Skip to content

Instantly share code, notes, and snippets.

View nklsrh's full-sized avatar

Nikhil Suresh nklsrh

View GitHub Profile
<!doctype html>
<html>
<head>
<title>Game</title>
<style>
body {
background-color: black;
}
#gameCanvas {
background-color: black;
// Lerp towards the ball on the y plane
paddle2DirY = (ball.position.y - paddle2.position.y) * difficulty;
// if ball goes off the 'left' side (Player's side)
if (ball.position.x <= -fieldWidth/2)
{
// CPU scores
score2++;
// update scoreboard HTML
document.getElementById("scores").innerHTML = score1 + "-" + score2;
// reset ball to center
// resets the ball's position to the centre of the play area
// also sets the ball direction speed towards the last point winner
function resetBall(loser)
{
// position the ball in the center of the table
ball.position.x = 0;
ball.position.y = 0;
// if player lost the last point, we send the ball to opponent
// Handles paddle collision logic
function paddlePhysics()
{
// PLAYER PADDLE LOGIC
// if ball is aligned with paddle1 on x plane
// remember the position is the CENTER of the object
// we only check between the front and the middle of the paddle (one-way collision)
if (ball.position.x <= paddle1.position.x + paddleWidth
&& ball.position.x >= paddle1.position.x)
// move left
if (Key.isDown(Key.A))
{
// code to move paddle left
}
...
var Key = {
_pressed: {},
A: 65,
W: 87,
D: 68,
S: 83,
// move left
if (Key.isDown(Key.A))
{
// if paddle is not touching the side of table
// we move
if (paddle1.position.y < fieldHeight * 0.45)
{
paddle1DirY = paddleSpeed * 0.5;
}
// else we don't move and stretch the paddle
// in case the Lerp function produces a value above max paddle speed, we clamp it
if (Math.abs(paddle2DirY) <= paddleSpeed)
{
paddle2.position.y += paddle2DirY;
}
// if the lerp value is too high, we have to limit speed to paddleSpeed
else
{
// if paddle is lerping in +ve direction
if (paddle2DirY > paddleSpeed)
// We lerp the scale back to 1
// this is done because we stretch the paddle at some points
// stretching is done when paddle touches side of table and when paddle hits ball
// by doing this here, we ensure paddle always comes back to default size
paddle2.scale.y += (1 - paddle2.scale.y) * 0.2;