Simple Interaction

Next, the goal is to tap the moving ball. So we need a way of interacting with the program. We will use a mouse function. Yes, an Android device has no mouse, but the touchscreen acts like one as far as Processing is concerned.

Try this simple program:

void setup()
{
  size(400,400);
}

void draw()
{
  ellipse(mouseX, mouseY, 40, 40);
}

Pretty cool, eh? mouseX,and mouseY are special variables. Anytime the mouse moves these are updated with the mouse position. In Android, or any touchscreen device, there is no mouse with out a touch. Android reads the touch as a mouse button press. We will make use of this in our game. Bring back your game code.
int xPos=200;
int xDir=1;

void setup()
{
  size (400,400);
  smooth();
  background(0);
  noStroke();
  fill(0,255,0);
}

void draw()
{
  background(0);
  ellipse(xPos, 200, 40, 40);
  xPos=xPos+xDir;
  if (xPos>width-20 || xPos<20)
  {
    xDir=-xDir;
  }
}

We're going to add a new function like draw and setup. This one will run whenever a mouse button is pressed. We also need to decide what happens if we hit the target. Let's make it get faster. We'll need a new variable for this.

int xPos=200;
int xDir=1;
int speed=1;

void setup()
{
  size (400,400);
  smooth();
  background(0);
  noStroke();
  fill(0,255,0);
}

void draw()
{
  background(0);
  ellipse(xPos, 200, 40, 40);
  xPos=xPos+xDir*speed;
  if (xPos>width-20 || xPos<20)
  {
    xDir=-xDir;
  }
}

void mousePressed()
{
  if (dist(mouseX, mouseY, xPos, 200)<=20)
  {
    speed=speed+1;
  }
}

I added several new things this time. Let's look at them one at a time. We added a new variable in our variable declaration at the beginning of the program int speed=1. If we hit the target speed increases by 1. We did this by changing:

xPos=xPos+xDir;   to    xPos=xPos+xDir*speed;

There's also a new function, void mousePressed(). This will run anytime the mouse is pressed or the screen is touched. So, how do we know if we hit the ball or not? that is in the line:

  if (dist(mouseX, mouseY, xPos, 200)<=20)

The dist() function has four parameters (x1, y1, x2,  y2). It will determine the exact distance between any two points. The Circle will be drawn at (xPos, 200) and has a radius of 20. So if the distance from the mouse coordinates to the center of the ball is less than 20 we hit it! This works because our object is a perfect circle if not we'd need another way to detect a hit. Here's one my students used for this program.

Comments