• Develop a Ping-Pong game using HTML5, CSS3 and JavaScript

    Published on November 15, 2011
    With 3 comments

    After this, we check for the top edge, left edge and right edge of the playground. If ball reaches the left or the right edge of the playground the ball position is reset (centered on the playground) and the score board is updated accordingly.

    The next step is to increment ball position on X and Y axis based on ball speed and orientation:

    After this we need to check if ball will “hit” the paddles and if it does, it has to bounce back on playground. In some circumstances, when ball is moving from top to bottom and passes very near to the top edge of the paddles without hitting it, after the ball passes behind paddle it bounces back on playground which is not a desirable effect. To avoid this we need to make a correction. Practically the game engine is set to perform calculation based on distance between the top/bottom edge of the paddle against top/bottom edge of the playground and the ball position, and to perform actions accordingly. So, making the ball top/bottom position against top/bottom edges of playground greater/smaller than the top/bottom paddles’ position against top/bottom playground’s edges will make the ball move more accurately.

    The last thing to do is to move the ball with speed and direction:

    Styling the elements

    I used some of the CSS3 style properties to give a neat appearance to this game. Unfortunately, not all the browsers’ engines implemented them in the general way, and to target them is necessary to use custom addressing (-o-, -webkit- and so on) to achieve the same effect. border-radius seems to be implemented in all major browsers, but transform, box-shadow, linear-gradient etc. are not. The game was tested on Mozilla Firefox, Safari, Google Chrome, Opera and Internet Explorer. Obviously the IE is making (as always) a different opinion so, it might look ugly (but the game functions well) to some corners ;) .

    Resources

    Please don’t use Space to pause the game if you play it on Internet Explorer (the alert message appears in game loop until the end of the game). I found a bug and need to fix it.
    Until I develop a convenient way yo pause the game, the pause action is disabled by default.

    A solution was found. Now the game flows as it should be. Enjoy it.

    DOWNLOAD
    source files
    PREVIEW
    live demo

    3 comments to "Develop a Ping-Pong game using HTML5, CSS3 and JavaScript"

    Share your thoughts on this article.

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">