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

2012/5/9

Calling an object's methods

dark_sky dark_sky

2012/5/9

#
Hello everyone, I'm coding a little game in which the player can jump against a box which should then perform an action. I get the object by
Actor box = getOneIntersectingObject(Box.class);
and then I want to call a specific method of this box, which is called bounce:
if(box != null) {
box.bounce();
}
But when I do it like this, it says "cannot find symbol - method bounce()" although i declared it in the Box class like this:
public void bounce() {
//do some stuff;
}
I'd be glad if you could help me fixing this!
danpost danpost

2012/5/9

#
The problem resides in the fact that the 'bounce()' method is in the Box class, NOT the Actor class. You will have to cast 'box' to a 'Box' before calling the method.
Box box = (Box) getOneIntersectingObject(Box.class);
dark_sky dark_sky

2012/5/10

#
Wow. Thank you for your help! But I got another question: Should I let the player detect the box and then call the method or should I let the box detect the player?
h123n h123n

2012/5/11

#
It doesn't really matter.You could program either one depending on which one is easiest.
IsVarious IsVarious

2012/5/24

#
A tip for code placement: It's normaly a good idea to put code in the place it makes the most sense, so for your example above. Are you wanting to player look for the box, or the box look for the player? it may seem like a subtle difference, but as a project expands, it does help to place code in natrualy logical locations.
You need to login to post a reply.