Friday, 4 March 2011

_08_SimpleGamePlay

int batX = 240;
int batY = 700;

int ballX = 240;
int ballY = 400;

int ballXspeed = 10;
int ballYspeed = 10;

//===================================
void setup() {
  size( 480, 800 );
  background( 0 );
}

//
//
//====================================
void draw() {
  background( 0 );
 
  moveTheBat();
  moveTheBall();
}


//
//This is just the same as in example 06
//====================================
void moveTheBat() {
  fill( 255 );
 
  batX = mouseX;
 
  //if the bat 'hits' the left edge move it back
  if( batX < 50 ) {
    batX = 50;
  }
 
  //if the bat 'hits' the right edge move it
  if( batX > 430 ) {
    batX = 430;
  }
 
  rect( batX - 50, batY, 100, 25 );
}

//
//This is basically the same as before except
//that this time, the ball doesn't bounce off
//the bottom of the screen.  Instead we use a
//function (not a built in one, we write it
//ourselves) to check if the ball hits the
//bat.
//=======================================
void moveTheBall() {
  ballX = ballX + ballXspeed;
  ballY = ballY + ballYspeed;
 
  if( ballX < 5 ) {
    ballX = 5;
    ballXspeed = ballXspeed * -1;
  }
 
  if( ballX > 475 ) {
    ballX = 475;
    ballXspeed = ballXspeed * -1;
  }
 
  if( ballY < 5 ) {
    ballY = 5;
    ballYspeed = ballYspeed * -1;
  }
 
  if( ballHitBat() ) {
    ballYspeed = ballYspeed * -1;
  }
 
  rect( ballX - 5, ballY - 5, 10, 10 );
}

//
//This function does the work of checking
//if the ball hits the bat.  There is a lot
//of new ideas in this small function.  First
//thing to notice is that the 'return type' of
//the function is 'boolean' instead of void.
//A boolean is a type of variable which can have
//the value 'true' or 'false'.  When the function
//detects that the ball and bat collide, it 'returns'
//the value 'true' as the answer.  We can use that
//answer somewhere else in the code to do something.
//If there hasn't been a collision then the function
//returns 'false'.  When a function 'returns' an answer
//it stops there and the program goes back to where ever
//it left off (which will be where ever the function
//was 'called').
//
//Another new idea introduced here is 'nested' if
//statements.  You can put an if test _inside_ another
//if test.  That way you can test for more complex
//situations.  _if_ the first test is true, then it
//checks the next test.  _if_ that's true then it
//checks the next one and so on.
//======================================
boolean ballHitBat() {
  if( ballY >= batY ) {
    if( ballX > batX - 50 ) {
      if( ballX < batX +50 ) {
        //the ball has hit the bat so return the answer is 'true'
        return true;
      }
    }
  }
  //if we get this far then the ball hasn't hit, return the answer 'false'
  return false;
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.