one way to do it is to have the computer follow the ball at a set speed. here is a very simple pong game i made a while ago. it's very unfinished, but it does illustrate this concept:
Code:
int ballx,bally,dir,pad_width,pad_height,ball_size,winner,hits;
float ball_speed,pad,Xpad;
void setup() {
size(800,600);
PFont font = loadFont("256Bytes-48.vlw");
textFont(font);
ballx=int(random(25, width-25));
bally=height/2-25;
pad=width/2-25;
Xpad=width/2-25;
dir = int(random(4));
pad_width=50;
pad_height = 10;
ball_size=50;
ball_speed = 5;
hits = 0;
}
void draw() {
update_display();
player_move();
com_move();
winner = ball_move();
println(hits);
if (winner == 1) {
text("You Win!",100,height/2) ;
}
if (winner == 2) {
text("Computer Wins!",80,height/2) ;
}
}
void update_display() {
background(0);
fill(255,50,50);
ellipse(ballx,bally,ball_size,ball_size);
fill(50,255,50);
rect(pad,height-10,pad_width,pad_height);
fill(50,50,255);
rect(Xpad,0,pad_width,pad_height);
}
void keyPressed() {
if (key == CODED) {
if (keyCode == LEFT)
pad_right();
if (keyCode == RIGHT)
pad_left();
}
}
void pad_right() {
if (pad > 0)
pad -= 5;
}
void pad_left() {
if (pad < width-pad_width)
pad += 5;
}
void com_move() {
if (ballx - ball_size/2 > Xpad) {
Xpad+=8;
}
if (ballx - ball_size/2 < Xpad)
Xpad-=8;
}
int ball_move() {
switch (dir) {
case 0:
ballx -= ball_speed;
bally -= ball_speed;
break;
case 1:
ballx += ball_speed;
bally -= ball_speed;
break;
case 2:
ballx += ball_speed;
bally += ball_speed;
break;
case 3:
ballx -= ball_speed;
bally += ball_speed;
break;
}
if (ballx <= ball_size/2){
if (dir == 0)
dir = 1;
if (dir == 3)
dir = 2;
}
if (ballx >= width - ball_size/2) {
if (dir == 1)
dir = 0;
if (dir == 2)
dir = 3;
}
if (bally - ball_size/2 <= 10) {
if ((ballx >= Xpad) && (ballx <= Xpad + pad_width)) {
if (dir == 0)
dir = 3;
if (dir == 1)
dir = 2;
}
else {
return 1;
}
hits++;
speed_change();
}
if (bally + ball_size/2 >= height - 10) {
if ((ballx >= pad) && (ballx <= pad + pad_width)) {
if (dir == 3)
dir = 0;
if (dir == 2)
dir = 1;
}
else {
return 2;
}
hits++;
speed_change();
}
return 0;
}
void speed_change() {
ball_speed += .02;
}
void player_move() {
pad = mouseX;
}