Jump to content
  • Advertisement
Sign in to follow this  
theodore italik

[web] Problem with javascript / HTML5 Pong

This topic is 2811 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey,

I'm not sure if this is a problem with my code (I've never programmed much in javascript before save a few small functions here or there) or what. Plus I'm fairly new to game programming.

The two problems I'm having are that the velocities sky rocket after a few hits, I thought my code for handling it was decent enough.

The second problem is that when I try to reset after the SECOND time a point is scored (i.e. when the ball has gone behind for a score) the game fails to reset and the score just increases until I refresh the browser.

Here is my code, like I said I'm very new to javascript so please forgive any obvious mistakes I've made (but I'd appreciate corrections / guidance):

Thanks for any advice / tips / help :)


var p1; // Player [[1]] Paddle
var p1Start = {X:[[50]], Y:[[250]]};
var p2; // Player [[2]] Paddle
var p2Start = {X:[[850]], Y:[[250]]};
var ball;
var ballStart = {X:[[450]], Y:[[10]]};
var paused = [[0]];
var ctx;
var canvas;
var canvasBuffer;
var intervalID = [[0]];

// check if the browser supports HTML5 Canvas objects
function checkIfSupported()
{
canvas = document.getElementById('pongCanvas');
if (canvas && canvas.getContext)
{
ctx = canvas.getContext('2d');
canvasBuffer = document.createElement('canvas');
canvasBuffer.width = canvas.width;
canvasBuffer.height = canvas.height;
canvasBufferContext = canvasBuffer.getContext('2d');

// new Paddle(position, width, height, colour, moveDistance, upper, lower);
p1 = new Paddle({X:[[50]], Y:[[250]]}, [[10]], [[75]], "rgb([[255]], [[255]], [[255]])", [[20]], [[0]], canvas.height - [[75]]);
p2 = new Paddle({X:[[850]], Y:[[250]]}, [[10]], [[75]], "rgb([[255]], [[255]], [[255]])", [[20]], [[0]], canvas.height - [[75]]);
// new Ball(position, radius, colour, velocity)
ball = new Ball({X:[[450]], Y:[[250]]}, [[8]], "rgb([[255]], [[255]], [[255]])", {X:-[[10]], Y:-[[4]]});
this.intervalID = setInterval(update, [[100]]);
}
else
{
alert('Your browser does not support the HTML5 Canvas object please try Chrome or Firefox.');
}
}

function update()
{
ball.Move();
// check for collisions
checkForCollisions();
// draw updated scene
draw();
}

// reset the paddles and ball to their starting positions
function reset()
{
canvasBufferContext.fillStyle = "rgb([[255]], [[255]], [[255]])";
canvasBufferContext.font = "[[10]] px console";
canvasBufferContext.textAlign = "bottom";
canvasBufferContext.fillText("Reset!",[[100]], [[450]]);
this.clearInterval(intervalID);
p1.position = p1Start;
p2.position = p2Start;
ball.position = ballStart;
// this.intervalID = this.setInterval(update, [[100]]);
}

function checkForCollisions()
{
// bounce it around the walls
if (ball.position['Y'] <= ball.radius)
{
// TOP WALL
ball.position['Y'] -= ball.velocity['Y'];
ball.velocity['Y']= -ball.velocity['Y'];
}
else if (ball.position['X'] < p1.position['X'])
{
// LEFT WALL
//ball.position['X'] -= ball.velocity['X'];
//ball.velocity['X'] = -ball.velocity['X'];
// player [[2]] scores
p2.score++;
reset();
}
else if (ball.position['X'] > (p2.position['X'] + p2.width) )
{
// RIGHT WALL
//ball.position['X'] -= ball.velocity['X'];
//ball.velocity['X'] = -ball.velocity['X'];
// player [[1]] scores
p1.score++;
reset();
}
else if (ball.position['Y'] >= canvas.height)
{
// BOTTOM WALL
ball.position['Y'] -= Math.round(ball.velocity['Y']);
// reverse direction
ball.velocity['Y']= -Math.round(ball.velocity['Y']);
}
// collides with player [[1]] on LHS of screen
else if ( (Math.abs(p1.position['X'] - ball.position['X']) <= ball.radius) && ( (ball.position['Y'] >= p1.position['Y']) && (ball.position['Y'] <= p1.position['Y'] + p1.height) ) )
{

// collision!
ball.hitCount++;
// update the ball's position
ball.position['X'] -= Math.round(ball.velocity['X']);
// reverse ball's velocity
ball.velocity['X'] = -Math.round(ball.velocity['X']);
// how close was it to the centre of the bat? close to centre = more power
var distToCentre = Math.abs((p1.position['Y'] + (p1.height / [[2]])) - ball.position['Y']);
// adjust ball's y velocity with a small random value
ball.velocity['Y'] += Math.round((distToCentre) * Math.random());
}
// collides with player [[2]] on RHS of screen
else if ((Math.abs((p2.position['X'] + p2.width) - ball.position['X']) <= ball.radius) && ( (ball.position['Y'] >= p2.position['Y']) && (ball.position['Y'] <= p2.position['Y'] + p2.height) ) )
{
// collision!
ball.hitCount++;
// update the ball's position
ball.position['X'] -= Math.round(ball.velocity['X']);
// reverse ball's velocity
ball.velocity['X'] = -Math.round(ball.velocity['X']);
// how close was it to the centre of the bat? close to centre = more power
var distToCentre = Math.abs((p2.position['Y'] + (p2.height / [[2]])) - ball.position['Y']);
// adjust ball's y velocity with a small random value
ball.velocity['Y'] += Math.round((distToCentre) * Math.random());
}


}

function draw()
{
canvasBufferContext.clearRect([[0]], [[0]], canvas.width, canvas.height);
ctx.clearRect([[0]],[[0]], canvas.width, canvas.height);
// draw scores
canvasBufferContext.fillStyle = "rgb([[255]], [[255]], [[255]])";
canvasBufferContext.font = "[[24]] px console";
canvasBufferContext.textAlign = "top";
canvasBufferContext.fillText(p1.score, [[200]], [[20]]);
canvasBufferContext.fillText(p2.score, [[700]], [[20]]);
// draw the 'net' in the middle
canvasBufferContext.fillStyle = "rgb([[50]],[[50]],[[50]])";
canvasBufferContext.fillRect((canvas.width / [[2]]) - [[10]], [[0]], [[10]], canvas.height);
// draw ball
canvasBufferContext.fillStyle = ball.colour;
canvasBufferContext.beginPath();
canvasBufferContext.arc(ball.position['X'], ball.position['Y'], ball.radius, [[0]], Math.PI*[[2]], true);
canvasBufferContext.closePath();
canvasBufferContext.fill();
// draw player [[1]] paddle
canvasBufferContext.fillStyle = p1.colour;
canvasBufferContext.fillRect(p1.position['X'], p1.position['Y'], p1.width, p1.height);
// draw player [[2]] paddle
canvasBufferContext.fillStyle = p2.colour;
canvasBufferContext.fillRect(p2.position['X'], p2.position['Y'], p2.width, p2.height);

canvasBufferContext.fillStyle = "rgb([[255]], [[255]], [[255]])";
canvasBufferContext.font = "[[10]] px console";
canvasBufferContext.textAlign = "bottom";
canvasBufferContext.fillText(ball.position['X'] + " " + ball.position['Y'], [[100]], [[400]]);
canvasBufferContext.fillText(ball.velocity['X'] + " " + ball.velocity['Y'], [[100]], [[480]]);

ctx.drawImage(canvasBuffer, [[0]], [[0]]);

}

// handle key press events
document.onkeydown = function(event){
var keyCode;

if(event == null)
{
keyCode = window.event.keyCode;
}
else
{
keyCode = event.keyCode;
}

switch(keyCode)
{
case [[32]]: // PAUSE
if (paused == [[0]])
{
this.clearInterval(intervalID);
paused = [[1]];
}
else if (paused == [[1]])
{
this.intervalID = setInterval(update, [[100]]);
paused = [[0]];
}
break;
case [[38]]: // UP ARROW
if (paused == [[1]])
{
// resume a paused game
paused = [[0]];
}
p2.tryMoveUp();
break;

case [[40]]: // DOWN ARROW
if (paused == [[1]])
{
// resume a paused game
paused = [[0]];
}
p2.tryMoveDown();
break;

case [[65]]: // UP (A)
if (paused == [[1]])
{
// resume a paused game
paused = [[0]];
}
p1.tryMoveUp();
break;

case [[90]]: // DOWN (Z)
if (paused == [[1]])
{
// resume a paused game
paused = [[0]];
}
p1.tryMoveDown();
break;
default:
break;
}
draw();
}

// 'constructor'
// @posn : 2d position on the canvas
// @r : radius of the ball
// @col : colour of the ball
// @speed : velocity of the ball
function Ball(posn, r, col, vel)
{
this.position = posn;
this.radius = r;
this.colour = col;
this.velocity = vel;
// Pong gets faster the longer a rally goes on
// so record the number of hits
this.hitCount = [[0]];
}

// move the ball around the screen
Ball.prototype.Move = function()
{
this.position['X'] += this.velocity['X'];
this.position['Y'] += this.velocity['Y'];
}

// 'constructor'
// @posn : 2d position on the canvas
// @w : paddle width
// @h : paddle height
// @col : paddle colour
// @moveDist : the distance a paddle moves
// @wUpper : top of the game world
// @wLower : bottom bound of the game world
function Paddle(posn, w, h, col, moveDist, wTop, wBott)
{
this.position = posn;
this.width = w;
this.height = h;
this.colour = col;
this.moveDistance = moveDist;
this.worldTop = wTop;
this.worldBottom = wBott;
this.score = [[0]];
}

// returns the position of the paddle IF it moved up
Paddle.prototype.getFutureUpPosition = function()
{
return this.position['Y'] - this.moveDistance;
};

// returns the position of the paddle IF it moved down
Paddle.prototype.getFutureDownPosition = function()
{
return this.position['Y'] + this.moveDistance;
};

// attempts to move UP the screen provided the Paddle
// won't go beyond the upper bound of the screen
Paddle.prototype.tryMoveUp = function()
{
var future = this.getFutureUpPosition();

if (future >= this.worldTop)
{
this.position['Y'] = future;
}
};

// attempts to move DOWN the screen provided the Paddle
// won't go beyond the lower bound of the screen
Paddle.prototype.tryMoveDown = function()
{
var future = this.getFutureDownPosition();

if (future <= this.worldBottom)
{
this.position['Y'] = future;
}
};



Share this post


Link to post
Share on other sites
Advertisement
// adjust ball's y velocity with a small random value
ball.velocity['Y'] += Math.round((distToCentre) * Math.random());


Are you sure the random value is small? At least in C rand() can generate numbers in thousands which you probably don't want.


And about the score.. It seems like you aren't reseting the ball's velocity so it might be so huge (because of the error above) it instantly moves behind the other paddle and just scores, resets, scores, resets and so on.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!