public class Ball extends Actor
{
int velX = Greenfoot.getRandomNumber(5)+3;
int velY = Greenfoot.getRandomNumber(5)+3;
public Ball()
{
GreenfootImage img = new GreenfootImage(20,20);
img.setColor(Color.WHITE);
img.fillRect(0,0,20,20);
setImage(img);
}
/**
* Act - do whatever the Ball wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
moveAndTurn();
paddleCollision();
score();
}
public void moveAndTurn()
{
setLocation(getX() + velX,getY() + velY);
if(getX() < 10 || getX() > getWorld().getWidth() - 10)
{
velX *= -1;
}
if(getY() < 10 || getY() > getWorld().getHeight() - 10)
{
velY *= -1;
}
}
public void paddleCollision()
{
Actor player1 = getOneIntersectingObject(Player1.class);
if(player1 != null)
{
setLocation(player1.getX()+20, getY());
velX *= -1;
}
Actor player2 = getOneIntersectingObject(Player2.class);
if(player2 != null)
{
setLocation(player2.getX()-20, getY());
velX *= -1;
}
}
public void score()
{
if(getX() <40)
{
PongWorld.player2Score ++;
setLocation(getWorld().getWidth()/2,getWorld().getHeight()/2);
}
if (getX() > getWorld().getWidth()- 40)
{
PongWorld.player1Score ++;
setLocation(getWorld().getWidth()/2,getWorld().getHeight()/2);
}
}
}

