Skip to content

Instantly share code, notes, and snippets.

View nklsrh's full-sized avatar

Nikhil Suresh nklsrh

View GitHub Profile
// if ball goes off the top side (side of table)
if (ball.position.y <= -fieldHeight/2)
{
ballDirY = -ballDirY;
}
// if ball goes off the bottom side (side of table)
if (ball.position.y >= fieldHeight/2)
{
ballDirY = -ballDirY;
// 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
// 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;
// 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)
// Lerp towards the ball on the y plane
paddle2DirY = (ball.position.y - paddle2.position.y) * difficulty;
// 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
...
var Key = {
_pressed: {},
A: 65,
W: 87,
D: 68,
S: 83,
// move left
if (Key.isDown(Key.A))
{
// code to move paddle left
}
function setup()
{
draw();
}
function draw()
{
<!doctype html>
<html>
<head>
<title>Game</title>
<style>
body {
background-color: black;
}
#gameCanvas {
background-color: black;