JavaScript Pong |
Written by Mike James | |||||
Friday, 24 December 2010 | |||||
Page 2 of 4
The Ball objectOf course we need a ball to bounce around the court and this is just another use of the CBlock object: CBall = function(position, Notice that we create a ball with the specified radius and store its position and velocity as new properties of the DOM object.
This particular new object has more than just properties, it also has a method that can be used to move it around the court: DOMObj.move = function() { The first pair of instructions add the velocity to the current position and the next pair up-date the ball's position. Notice that in this case we have to use “this” to provide the context of the call because when the method is used “this” will be set to the current instance of the ball and the DOMObj variable will be long gone. In general use the DOM object reference when creating properties and methods on the object but use “this” when an instance is going to be accessing the properties and methods. The final part of the move method simply checks to see if the ball has hit the side of the court or has gone out of play: this.play = 0; Notice the use of the play property to signal that the ball is or is not in play. A bounce is implemented by simply reversing the appropriate velocity. It was tempting to add a “beep” noise to the bounce but this isn’t easy within a browser as JavaScript has no “beep” or noise making command. Now that we have a ball to play with we simply add it to the court with an initial position and velocity: Ball = new CBall( BatsThe next task is to create a bat object and two instances of it, one for each bat. CBat = function(position, size) { DOMObj.hit = function(B) { The bat needs two methods – a move method which simply allows the bat to move up or down and a hit testing method which tests to see if the bat has hit the ball passed as parameter B. Notice that we could dispense with the property p and simply use style.top and style.left and the same with s and style.width and style.height but it is easier to have integer versions of these string style properties rather than keeping on having to type convert them. Creating two bats is now very easy, which is one of the advantages of the object-oriented approach: BatL = new CBat( We now have a court, a net, two bats and a ball but nothing moves: <ASIN:1430210664> <ASIN:0596101996> <ASIN:1590596803> |
|||||
Last Updated ( Sunday, 10 July 2022 ) |