So far everything works except resetting the location of the pear when it hits the right edge of the screen. each pear moves 20 cells right when the Block class bounces off a wold edge. The pear should move from the right edge on contact to the same height on the left edge. the movePears() method should be able to do this but nothing I've tried works correctly.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
* A block that bounces back and forth across the screen.
*
* @author Michael Kölling
* @version 1.0
*/
public class Block extends Actor
{
private int delta = 2;
double dx;
double dy;
/**
* Move across the screen, bounce off edges. Turn leaves, if we touch any.
*/
public void act()
{
move();
checkEdge();
checkLeaf();
checkMouseClick();
turnApples();
movePears();
}
/**
* Move sideways, either left or right.
*/
private void move()
{
setLocation(getX()+delta, getY());
}
/**
* Check whether we are at the edge of the screen. If we are, turn around.
*/
private void checkEdge()
{
if (isAtEdge())
{
delta = -delta;
}
}
/**
* Check whether the mouse button was clicked. If it was, change all leaves.
*/
private void checkMouseClick()
{
if (Greenfoot.mouseClicked(null))
{
World world = getWorld();
List<Leaf> leaves = world.getObjects(Leaf.class);
for (Leaf leaf : leaves)
{
leaf.changeImage();
}
}
}
/**
* Check whether we're touching a leaf. If we are, turn it a bit.
*/
private void checkLeaf()
{
Leaf leaf = (Leaf) getOneIntersectingObject(Leaf.class);
if (leaf != null) {
leaf.turn(9);
}
}
/**
* Method to turn apples 90 degrees when Block hits an edge
*/
public void turnApples()
{
if (isAtEdge() == true)
{
World world = getWorld();
List<Apple> apples = world.getObjects(Apple.class);
for (Apple apple : apples)
{
apple.turn(90);
}
}
}
/**
* Method to move Pears 20 cells to the right and
* move them to the opposite edge if at the world edge
*/
public void movePears()
{
if (isAtEdge() == true)
{
World world = getWorld();
List<Pear> pears = world.getObjects(Pear.class);
//if (isAtEdge() == false)
for (Pear pear : pears)
{
{
pear.move(20);
if (getX() == getWorld().getWidth()) {
pear.setLocation(0, getY ());
}
}
}
}
}
/**
* Test if we are close to one of the edges of the world. Return true is we are.
*/
public boolean atWorldEdge()
{
if(getX() < 20 || getX() > getWorld().getWidth() - 20)
return true;
if(getY() < 20 || getY() > getWorld().getHeight() - 20)
return true;
else
return false;
}
}
