Hi
I've some trouble making the balls bounce, when they hit the four walls.
My code has been posted below.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Ball here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Ball extends Actor
{
private Vector Vel;
public Ball(int xVel, int yVel)
{
Vel = new Vector(xVel, yVel);
}
public void act()
{
handleWallCollision();
move();
}
public void move()
{
int x = getX() + Vel.getX();
int y = getY() + Vel.getY();
setLocation(x, y);
}
public boolean hitTopWall()
{
if(getY()+getImage().getHeight()/2 > 0)
{
return true;
}
else
{
return false;
}
}
public boolean hitBottomWall()
{
if(getY()+getImage().getHeight()/2 < getWorld().getHeight()-1)
{
return true;
}
else
{
return false;
}
}
public boolean hitLeftWall()
{
if(getX()+getImage().getWidth()/2 < 0)
{
return true;
}
else
{
return false;
}
}
public boolean hitRightWall()
{
if(getX()+getImage().getWidth()/2 > getWorld().getWidth()-1)
{
return true;
}
else
{
return false;
}
}
public void handleWallCollision()
{
if(hitRightWall())
{
Vel.horizontalFlip();
}
else if(hitLeftWall())
{
Vel.horizontalFlip();
}
else if(hitBottomWall())
{
Vel.verticalFlip();
}
else if(hitTopWall())
{
Vel.verticalFlip();
}
}
}
