Skip to content

Instantly share code, notes, and snippets.

@nklsrh
Created July 10, 2013 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nklsrh/5963058 to your computer and use it in GitHub Desktop.
Save nklsrh/5963058 to your computer and use it in GitHub Desktop.
// 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 aligned with paddle1 on y plane
if (ball.position.y <= paddle1.position.y + paddleHeight/2
&& ball.position.y >= paddle1.position.y - paddleHeight/2)
{
// 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
// this is not realistic physics, just spices up the gameplay
// allows you to 'slice' the ball to beat the opponent
ballDirY -= paddle1DirY * 0.7;
}
}
}
// OPPONENT PADDLE LOGIC
// if ball is aligned with paddle2 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 <= paddle2.position.x + paddleWidth
&& ball.position.x >= paddle2.position.x)
{
// and if ball is aligned with paddle2 on y plane
if (ball.position.y <= paddle2.position.y + paddleHeight/2
&& ball.position.y >= paddle2.position.y - paddleHeight/2)
{
// and if ball is travelling towards opponent (+ve direction)
if (ballDirX > 0)
{
// stretch the paddle to indicate a hit
paddle2.scale.y = 15;
// switch direction of ball travel to create bounce
ballDirX = -ballDirX;
// we impact ball angle when hitting it
// this is not realistic physics, just spices up the gameplay
// allows you to 'slice' the ball to beat the opponent
ballDirY -= paddle2DirY * 0.7;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment