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

2012/2/17

Teleporting crab

Nemean Nemean

2012/2/17

#
Hey im having a little issue with the .setLocation method. This is what I have for my code....
public void checkKeypress()
    {
       int num1 = Greenfoot.getRandomNumber(560);
       int num2 = Greenfoot.getRandomNumber(560);
        if (Greenfoot.isKeyDown("up"))
        {
            move();
        }
        if (Greenfoot.isKeyDown("down"))
        {
            turn(180);
        }
        if (Greenfoot.isKeyDown("left")) 
        {
            turn(-4);
        }
        if (Greenfoot.isKeyDown("right")) 
        {
            turn(4);
        }
        if (Greenfoot.isKeyDown("space"))
        {
            Crab.setLocation(num1, num2);
        }
    }   
when i compile I get "non - static method setLocation can not be reference from a static context". I thought this was something to do with the random number generator, but from what i have seen this is correct in greenfoot.
Nemean Nemean

2012/2/17

#
Never mind i just tried removing crab. and it worked.
Duta Duta

2012/2/18

#
The problem is as I said over at http://www.greenfoot.org/topics/869 a few days ago (parts of this answer are the same as what I said in that topic): The problem is that you're trying to do <A class>.<A method> (in this case Crab.setLocation(num1, num2)) which you can only do if the method is static - what you need to do is have <An object>.<A method> (so, aCrab.setLocation(num1, num2)) To do this, change the following (lines 21-24 of your posted code):
if(Greenfoot.isKeyDown("space"))
{
    Crab.setLocation(num1, num2);
}
to this instead:
if(Greenfoot.isKeyDown("space") && !getWorld().getObjects(Crab.class).isEmpty())
{
    Crab aCrab = (Crab) getWorld().getObjects(ant2.class).get(0);
    aCrab.setLocation(num1, num2);
}
Note that this will only work if you only have one object of Crab.class in the world - any more than that and it will just do it for one of the crabs.
danpost danpost

2012/2/18

#
^Duta would be correct, if you were not coding this in the Crab class. However, from your last post, it appears you ARE in the Crab class. Also, what would work is
this.setLocation(num1, num2);
Duta Duta

2012/2/19

#
Oh I see - that explains why removing Crab. worked (I didn't understand what he meant by that, I thought maybe he'd removed the actual crab from the world for some reason!) I guess that'll teach me to write posts when in a hurry
danpost danpost

2012/2/19

#
@Duta, Do not sweat it! We all, or most of us, at least, are guilty of it from time to time. We are so eager to help that we miss the clues that matter. Again, it would have helped had the information been provided. We keep stressing the need for clarity, so the help can be more tailored to their needs.
You need to login to post a reply.