14 March 2012

Coursework 1: JavaScript Animation Game– Post 1



Paper Toss
For my first coursework in the client/server web technologies module, I was tasked with creating a simplified version of the popular game called Paper Toss. 

The requirements of the coursework state that; the application must be done using raw HTML and JavaScript (no APIs are allowed to be used), provide the user with some form of controls, animate an image (in this case a paper ball) and implement collision detection functionality.


I divided this task into multiple smaller ones in order to tackle one problem at a time and created the following to do list (you could use this list as your steps to creating a similar application):
  1. Make an image move on screen.
  2. Make the image go back to its starting position.
  3. Disable any important controls programmatically while the animation is in process.
  4. Make the paper go up and then back down.
  5. Collision detection.
  6. Provide the user with control of the shooting angle.
  7. Provide the user with control of the shooting power.
  8. Make the paper ball roll while moving in the air.
In this post I will cover the first two tasks in this list and will post about the rest later.


Making an image move on screen

For this task it is best if you start slow, set a very low benchmark for your goal and then gradually elaborate. I will explain how to animate your image or object in a moment.

I first started out by creating the object I want to animate and that’s the paper ball, so I downloaded an image I liked and saved its format to JPEG as this is a good compression format and keeping in mind that this is a web based application you don’t want your users to waste their precious bandwidth on ill compressed images (come on be sensible!).

The next step was to display my paper ball in the browser, a task easily achieved by using the <IMG> element tag and setting its ‘src’ attribute to the image’s location. I also inserted the <IMG> tag within a <DIV> element, this will be my game area on the screen.


 <div id="GameArea" style="padding-top:400px;  width: 100%">
    <img id="paper" src="paper.jpg" alt="Image Not Found" style="width: 40px;height: 40px"/>
 </div>

As you may have noted I also inserted some in-line CSS, such as; the width and height of the paper ball, the width and top padding of the game area and I also set a unique identifier to both elements so I could reference them in my JavaScript code later on.

Now, displaying images on screen is all good fun, but I want to programmatically move this image and for that I’m going to need some JavaScript, so here we go!

To be able to change the position of the paper ball I retrieved it via the ‘document.getElementById()’ function and passed it the unique identifier given to the paper ball object I mentioned earlier. Once I retrieved it, I stored it in a global variable named ‘myPaper’ in order to store it in memory. Then I:
  1. Set its position property to ‘relative’ in-order to make this object movable.
  2. Set its left property to 0px (this specifies the x-coordinate from the left of the parent container).
  3. Set its top property to -21px in order to lift it up a bit from the bottom (this specifies the y-coordinate from the top of the parent container).
  4. Created a function named ‘move()’ which adds 10 pixels to the paper object’s left property, like so:
       function move(){
       myPaper.style.left = parseInt(myPaper.style.left)+10+'px');
       }

When this function is called the paper ball gets moved to the right by 10 pixels, but don’t call this an animation just yet, the paper ball must move much more than a mere 10 pixels. To solve this is simply call the ‘move()’ function for multiple times but I do this by using ‘setInterval()’. This JavaScript function requires 2 parameters; the function name it must call and the time in milliseconds to wait between each call.

       //every 40 milliseconds setInterval() will call the move() function
       motion = setInterval(move,40);

Now, the paper ball kept on moving to the right, 10 pixels at a time, but wait!! The paper will not stop moving now until I tell it to. In order to do so I used another JavaScript function, called ‘clearInterval()’. This function only requires one parameter, and that’s the object representing the ‘setInterval()’. As you can see in the above code, I stored the ‘setInterval()’ action in a global variable named ‘motion’, therefore I can pass the ‘motion’ variable to the ‘clearInterval()’ function and as soon as this code is executed my paper ball stops moving.

But when should this peace of code be executed? To answer my question I decided that the paper should stop when it reaches the other end of the user’s browser screen. But I can’t just define the same screen width for every user, can I? I know two ways to identify the user’s screen width:

  1.  window.innerWidth
  2.  screen.availWidth


Both these methods return the user’s screen width, but I prefer the first option, because ‘window.innerWidth’ returns the actual width of the Browser’s screen. While ‘screen.availWidth’ returns the width of actual device’s screen.  This might not matter much if the browser window is maximised, but what if it’s set to half the width of the device screen and set to one side? Now it makes sense…does it!


Make the image go back to its starting position

Now after you enjoyed making your object move from one side to the other, you probably want to know how to reset it in order to do it all over again. The answer is simple, just create a function which will be used for resetting all your values to the original ones and call this function when some action takes place.

I decided that I wanted a Reset button in my game, so I added one and set its ‘onClick’ attribute to call this function, which I named ‘start()’.

Apart from using this function to reset my values I also decided to use this once the body of my HTML page has loaded, by setting the ‘onLoad’ attribute of the body tag like so:

<body onLoad="start()">
….
<body>

So I will also use it to:
  • Call a function named ‘getScreenSize()’, this identifies the width and size of the browser screen how I explained earlier and stores the values globally.
  •  Initialize the ‘myPaper’ object and its settings.
  •  Clear any on-going motion interval at the start of my web.

       function start(){
            //gets the user's screen size and stores the width and height in variables
            getScreenSize();

            //gets the paper image and stores it as an object in myPaper
            myPaper=document.getElementById('paper');
            myPaper.style.position='relative';
            myPaper.style.left = '0px';
            myPaper.style.top = '-21px';

       clearInterval(motion);
       }

That’s it for today’s post, below is an image illustrating what has been created so far.


The paper ball moves to the right when the 'Throw' button is
 clicked and goes back to it's original position once the 'Restart'
button is pressed.




I will write another post later, covering the third and fourth steps I mentioned at the beginning of this blog.

No comments:

Post a Comment