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

2013/9/10

getLocation

mattjames mattjames

2013/9/10

#
Hi I want to get the location of a car, but so far the code will not do this. Here is the code that does this:
public void atbasecamp(){
        int locationy =getY();
        int locationx =getX();

        int basecamptestlocationX;
        basecamptestlocationX=locationx;

        int basecamptestlocationy;
        basecamptestlocationy=locationy;

        if(locationx==6&&locationy==3){
            basecampunload();

        }
        else{
            wintester();

        }
    }
Can anybody see any problems? Thanks
SPower SPower

2013/9/10

#
That's because the locationy and locationx variables are declared at the top of your class: this causes them to be initialized when an object is created. But, the object is not yet in a world, so you get an exception. You need to update them every time you use them, so it might be easier just to use the getX and getY methods instead of refreshing those 2 variables constantly. And to get back to your question, you will need to move the variables to the method addedToWorld:
protected void addedToWorld(World w)
{
    // your code here
}
which gets executed when an Actor gets added to a World. And some advice, your method is called 'atbasecamp', which might be hard to read for some, because you're not using capitals to denote new words. So 'atBaseCamp' would be better. This also applies for locationx and locationy, they should be 'locationX' and 'locationY'
danpost danpost

2013/9/10

#
@SPower, it appears to me that they are being declared in a method (not the top of the class). @mattjames, The code provided is equivalent to the following:
public void atbasecamp()
{
    if (getX() == 6 && getY() == 3) basecampunload(); else wintester();
}
There does not appear to be any problems with the code itself; but for the apparent excessive use of local fields (or variables) which are not passed to any of the method calls or saved in any instance or class fields -- so are immediately flagged for garbage collection when the method completes.
SPower SPower

2013/9/10

#
@danpost sorry, first I though that atbasecamp was his class name, but later I realised it's a method name and I didn't change my story :( Sorry.
You need to login to post a reply.