Hi all. i was wondering if somebody could explain how I can get a variable I have created in one actor to be used in other actors and also in my world classes. Thanks.
// from the world
int sharedValue = ((Sharing) getObjects(Sharing.class).get(0)).getShared();
// or from an actor
int sharedValue = ((Sharing) getWorld().getObjects(Sharing.class).get(0)).getShared();
// using this method in the 'Sharing' class
public int getShared()
{
return shared;
}// from the world
int sharedValue = ((Sharing) getObjects(Sharing.class).get(0)).getShared();
// or from an actor
int sharedValue = ((Sharing) getWorld().getObjects(Sharing.class).get(0)).getShared();
// using this method in the 'Sharing' class
public int getShared()
{
return shared;
}public class Road extends World
{
// Variables Defined
// PSH = Player Start Height
// PSH2 = Player 2 Start Height
// middle = middle of the world's width
// origin is the center height of the world
// TSP = Treasure Starting Point
// D2T = Distance 2 Treasure
int middle = getWidth() /2 - 10 ;//Subtracted 10 to make finish class coincide with grid background
int origin = getHeight() /2;
int ran1 = getHeight();
int ran2 = getWidth();
int PSH = getHeight() /4 + origin;// added origin to the equation to the current player spawn point
int P2SH = getHeight() /6;
int TSP = Greenfoot.getRandomNumber(ran2);
int D2T = TSP - middle;
int P2T = ((Actor) getObjects(Player2.class).get(0)).getTime();
/**
* Constructor for objects of class Road.
*
*/
public Road()
{
// Create a new world with 2000x200 cells with a cell size of 1x1 pixels.
super(2000, 200, 1);
FinishLine finishline = new FinishLine();
addObject(finishline, middle, origin);
Player player = new Player();
addObject(player, middle, PSH);
Player2 player2 = new Player2();
addObject(player2, middle, P2SH);
Treasure treasure = new Treasure();
addObject(treasure, TSP, PSH);
Treasure treasure2 = new Treasure();
addObject(treasure2, TSP, P2SH);
background();
}
public int treasureDistance()
{
return D2T;
}
public void background()
{
GreenfootImage img = getBackground();
img.setColor(java.awt.Color.white);
img.fillRect(800,65,450,50);
img.setColor(java.awt.Color.black);
img.drawString("vvvv", 100, 50);
setBackground(img);
}
}public class Player2 extends Actor
{
private int limit = 1;
private int steps = 0;
public int time = 0;
/**
*
*/
public void act()
{
move();
}
public void move()
{
move(1);
steps = steps + 1;
if (steps == limit)
{
turn (180);
steps = 0;
limit = limit*2;
}
TouchingTreasure();
time = time + 1;
}
public void TouchingTreasure()
{
Actor treasure = getOneObjectAtOffset(0, 0, Treasure.class);
if (treasure !=null)
{
System.out.println("Good Job Player 2! You have found the Treasure after: " + time/60 + " Seconds" +((Road)getWorld()).treasureDistance()+ " Pixels Away");
getWorld().removeObject (this);
}
}
public int getTime()
{
return time;
}
}