object may be like a stone , ball , etc.
public void bounceOffWorldEdge() {
if (getX() < 20) {
if (getRotation() < 180) {
setRotation(180-getRotation());
}
else if (getRotation() >= 180) {
setRotation((180-getRotation()));
}
if (getX() < 20) {
for (int i = 0; i < 5 && getX() < 20; i++) {
setLocation(getX()+5, getY());
}
}
}
else if (getX() > getWorld().getWidth()-20) {
if (getRotation() <= 90) {
setRotation(180-getRotation());
}
else if (getRotation() > 270) {
setRotation(180+(360-getRotation()));
}
if (getX() > getWorld().getWidth()-20) {
for (int i = 0; i < 5 && getX() > getWorld().getWidth()-20; i++) {
setLocation(getX()-5, getY());
}
}
}
else if (getY() < 20) {
if (getRotation() <= 270) {
setRotation(90+(270-getRotation()));
}
else if (getRotation() > 270) {
setRotation(90-(getRotation()-270));
}
if (getY() < 20) {
for (int i = 0; i < 5 && getY() < 20; i++) {
setLocation(getX(), getY()+5);
}
}
}
else if (getY() > getWorld().getHeight() - 20) {
if (getRotation() <= 90) {
setRotation(270+(90-getRotation()));
}
else if (getRotation() > 90) {
setRotation(270-(getRotation()-90));
}
if (getY() > getWorld().getHeight() - 20) {
for (int i = 0; i < 5 && getY() > getWorld().getHeight() - 20; i++) {
setLocation(getX(), getY()-5);
}
}
}
}// for a world class act method
public void act()
{
if (Greenfoot.getRandomNumber(100) < 2)
{
int rand = Greenfoot.getRandomNumber(2);
addObject(new Ball(1-2*rand), (getWidth()-1)*rand, 32);
}
}
// for the Ball class, use the following instance fields
int direction; // horizontal direction; assigned in constructor
int vSpeed = 0; // vertical speed
int hSpeed = 2 // horizontal speed; adjust as needed
// for the Ball constructor
public Ball(int dir)
{
direction = dir; // save horizontal direction to move
}
// Ball class act method
public void act()
{
setLocation(getX(), getY()+(++vSpeed)); // move vertically adding gravity
if (getY() >= getWorld().getHeight()-getImage().getHeight()/2 && vSpeed > 0) vSpeed = -vSpeed; // check height, bounce
setLocation(getX()+direction*hSpeed, getY()); // move horizontally
if (getX()-(getWorld().getWidth()-1)*(direction+1)/2 == 0) getWorld().removeObject(this); // check edge, remove
}