|
Greenfoot Lesson: Movement
How to make things move Part II
Movement Tutorial II
If you want to move an object in Greenfoot when it is intitialized you cannot do so directly in the constructor.
You must create a method called
addedToWorld().
| Erroneous Code (tries using constructor) |
Proper Code |
public Wombat()
{
setLocation(1,1);
} |
public void addedToWorld(World world)
{
setLocation(1,1);
} |
How to tell your location
| Method |
Meaning |
| int getY() |
returns an int that is the column value or y-cordinate of a tile |
| int getX() |
returns an int that is the row value or x-cordinate of a tile |
How far to the edge of the world?
To be able to tell how far to the edge of a world you must
getX() vs width of the world
The picture below illustrates the values that getX() stores. NOTE: the getWidth() method of the world is 8 but the last value of getX() on the grid is 7.


Te first thing to look at is location changes. Consider, for example, the following code:
public void act()
{
int x = getX();
int y = getY();
//move 1 to right
setLocation(x + 1, y);
}
My Students: create a new subclass of Actor called person. Copy and paste all of the code below into the class. Run the code and try to learn from what's printed out.
Labs
Lab #1 ) Create a new class called WombatSearcher()
- You should be able to put a WombatSearcher() down anywhere on the grid. The first thing that it will do is randomly dhoose one of the four corners
- travel to that corner
- then it will traverse every row and column until it has visited all the cells and eaten ALL of the leaves that are on the grid
|