1 – THE PADDLE CLASS OBJECTS Our Pong game will have two types of objects. A ball object and two copies of the paddle
object. We will start working with the
paddle class. PADDLE CHARACTERISTICS We have to consider the properties required to
define a paddle. First, there is
certainly the location of the paddle on screen. So we need two float variables that hold
the coordinates. Second, the paddle’s
size should be defined as well. So we have the following datafields: private float x; private float y; private final float width; private final float height; CONSTRUCTOR We will create a constructor that simply gets a
value for each datafield. public Paddle(float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; this.height = height; } GET METHODS We will now create simple get methods for each of
the four datafields. public float getX() { return x; } public float getY() { return y; } public float getWidth() { return width; } public float getHeight() { return height; } CONSIDERING OTHER METHODS Now we need to ask ourselves if we need any other methods? We don’t
need to change the value of x. At
least for now, we don’t need to change the size of the paddle either. But we do need to be able to change the
y-coordinate of the paddle. THE setY METHOD While a simple method that allows us to simply set y
to any value desired would work, we can also make sure that y is a value that
is on the screen. We will do this. Essentially, our strategy is simple. We set y to the new value. If that value is below zero, we set y to
zero. If that value is above the top
of the screen, we set it to the top of the screen. There is one extra complication regarding the top of
the screen. The x and y of our paddle
actually refer to the bottom left corner of the paddle. So, the paddle is at the top of the screen
when the y coordinate is equal to the height
of the room minus the height of the
paddle. public void setY(float newY) { y = newY; if(y < 0) { y = 0; } else if(y > Gdx.graphics.getHeight()
- height) { y = Gdx.graphics.getHeight()
- height; } } Note: There is one weakness with the code
above. It assumes that the paddle will
operate on the entire room. If we
wanted to make the game take up only a part of the screen, we would have to
make modifications. |
|
|