July 1, 2015 10:48 am

Creating a game with JavaScript and Processing.js part 3

The next method is a bit lengthy and it involves all collision tests as well as some image visualizations. First, we loop for each star the player has launched and if any of the stars is behind the left edge of the screen, we remove it and continue with the next star. If it is not, we move it to the right, display it and check if it has hit the enemy. If it indeed hit the enemy – we reduce the enemy’s lives by 1 and empty all player stars.

Creating a game with JavaScript and Processing.js part 1

After that, we display the player and check if he has collided with the enemy – if it is we call the onLifeLost() method. In the end, we move the enemy’s stars by a semi-random number and change their size randomly and check if the player has collided with a star of the enemy – if it has – we call the onLifeLost() method again.

Creating a game with JavaScript and Processing.js part 1

Creating a game with JavaScript and Processing.js part 2

Afterwards, we define the game menu (when a game has finished or the user has just entered the game) which displays some static text and the results so far.

In the end, we define the draw function which will be called all the time (like what setInterval() does) in which if the game is running, we will initialize the CosmicFighter object and if it is not running – we display the menu. We also check if any of the buttons are clicked and perform the appropriate action, if clicked.

Conclusion

By now, you should have some idea of how to create a game relying either on the HTML5 Canvas API or both canvas and Processing.js

Processing.js may transform the low-level canvas drawing to a higher level but both are a great addition to the Web and can be seen as decent substitutes of the Flash snippets and even games we could find before all over the Internet.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories: