This site requires JavaScript, please enable it in your browser!
Greenfoot back
NIRO17
NIRO17 wrote ...

2016/9/12

passing variables

NIRO17 NIRO17

2016/9/12

#
I want to pass the value of "man2Distance" in man2 class to man1 class..because i want to compare each values inside the man1 class..how can i do it. here is my man1 class

public class man1 extends Actor
{
    
    public static int man1X, man1Y;
    public void act() 
    {
        man1X=getX();
        man1Y=getY();
        moveAround(); 
    }    

    public void moveAround(){

        double man1Distance = Math.sqrt((getX() - Barrel.B1X)*(getX() - Barrel.B1X)+(getY() - Barrel.B1Y)*(getY() - Barrel.B1Y));
      
        
        if (man1Distance > 100)
        {
             move(4);
        if(Greenfoot.getRandomNumber(100)<10){
            turn(Greenfoot.getRandomNumber(180)-90);
        } 
        }
        else {
            move(1);
        }
      
    }
}
[\code]





here is my man2 class

[code]
public class man2 extends Actor
{
  
    
    public static int man2X, man2Y;
   
    public void act() 
    {
        man2X=getX();
        man2Y=getY();
    }   
    
      public void moveAround(){
       double man2Distance = Math.sqrt((getX() - Barrel.B1X)*(getX() - Barrel.B1X)+(getY() - Barrel.B1Y)*(getY() - Barrel.B1Y));
      
     
 
}
 
}



danpost danpost

2016/9/12

#
The coordinate locations of all objects in the world are already stored in the 'x' and 'y' (hidden) fields provided by the Actor class. These values, furthermore, can be obtained by the use of the 'getX' and 'getY' methods of the Actor class. So, for example, to get the coordinates of the man2 object from the man1 class:
if (!getWorld().getObjects(man2.class).isEmpty()) // check to see if a man2 object is in the worl
{
    Actor m2 = (Actor)getObjects(man2.class).get(0); // gets reference to a man2 object
    // the followin set local variables to coordinates of man2 object
    int man2x = m2.getX();
    int man2y = m2.getY();
    // do whatever with values and perform some possible action here
}
A few things to note: * using 'static' fields, or class fields, for information that belong to objects of the class is not recommended; * using any field for information that can already be obtained by methods calls is not recommended; * there is a 'Math.hypot' method that can simplify your expressions on lines 14 and 52;
You need to login to post a reply.