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

2018/1/19

Can't find method

Nyoki Nyoki

2018/1/19

#
I am creating a game (for a project) where if the character ( controlled by keyboard) which is a penguin touches a fishnet, there will be 2 fish appearing on the screen. I have the method in my penguin class. However, when I transported this method to my world (which is called arctic), it appears as if my world can't find the method. This is my code in the penguin class (this is without error) public boolean isTouchingNet() { Actor net = getOneObjectAtOffset(0,0,fishnet.class); if (net != null) { return false; } return true; } This is the code from my world (this has an error it says that it can't find the method "isTouchingNet()" public void addFish() { Actor penguin = (penguin) getObjects(penguin.class).get(0); Actor fish = (fish) getObjects(fish.class).get(0); if (penguin.isTouchingNet()= true) { addObject (fish, 300, 400); // this needs to be change into random addObject (fish, 300, 500); }
Yehuda Yehuda

2018/1/19

#
If you're checking for equality you should use two equal signs (==), using one sign is for storing a value. A different problem with your code is the 'isTouchingNet' method will always return true unless the middle of the penguin is touching a Fishnet (you reversed the placement of "true" and "false").
danpost danpost

2018/1/19

#
The main problem is that 'penguin' is an Actor type variable -- not a penguin type variable. It will not look in the penguin class for a method unless the variable is of type penguin (or a subclass of the penguin class). However, you can cast 'penguin' to be of type penguin when you call the method:
if ( ((penguin)penguin).isTouchingNet() )
The '== true' part is not necessary as 'isTouchingNet' has a boolean return type (it is 'true' or 'false' already). However. as Yehuda has already pointed out, the returned value is opposite of what the name of the method suggests (should be "if not null, return true else return false"). A simplification can be done there as well:
public boolean isTouchingNet()
{
    return getOneObjectAtOffset(0, 0, fishnet.class) != null;
}
Nyoki Nyoki

2018/1/20

#
ok! Thank you very much !
You need to login to post a reply.