Skip to content

Instantly share code, notes, and snippets.

View nklsrh's full-sized avatar

Nikhil Suresh nklsrh

View GitHub Profile
// update the board to reflect the max score for match win
document.getElementById("winnerBoard").innerHTML = "First to " + maxScore + " wins!";
// we can easily notice shadows if we dynamically move lights during the game
spotLight.position.x = ball.position.x;
spotLight.position.y = ball.position.y;
// create a point light
pointLight = new THREE.PointLight(0xF8D898);
// set its position
pointLight.position.x = -1000;
pointLight.position.y = 0;
pointLight.position.z = 1000;
pointLight.intensity = 2.9;
pointLight.distance = 10000;
scene.add(pointLight);
paddle1 = new THREE.Mesh(
new THREE.CubeGeometry(paddleWidth, paddleHeight, paddleDepth, paddleQuality, paddleQuality, paddleQuality),
paddle1Material);
// add the sphere to the scene
scene.add(paddle1);
paddle1.receiveShadow = true;
paddle1.castShadow = true;
// checks if either player or opponent has reached 7 points
function matchScoreCheck()
{
// if player has 7 points
if (score1 >= maxScore)
{
// stop the ball
ballSpeed = 0;
// write to the banner
document.getElementById("scores").innerHTML = "Player wins!";
// game-related variables
var score1 = 0, score2 = 0;
// you can change this to any positive whole number
var maxScore = 7;
// 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)
// and if ball is travelling towards player (-ve direction)
if (ballDirX < 0)
{
// stretch the paddle to indicate a hit
paddle1.scale.y = 15;
// switch direction of ball travel to create bounce
ballDirX = -ballDirX;
// we impact ball angle when hitting it
// 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)
{
// and if ball is aligned with paddle1 on y plane
if (ball.position.y <= paddle1.position.y + paddleHeight/2
// 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