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

2014/11/30

Need help with addObject

qwerty1 qwerty1

2014/11/30

#
Hello! I need some help with the addObject method. I'm trying to make it so that when the user-controlled player1 touches the endLevel1 actor(a yellow dot), the level ends with the Win actor being added onto the screen which will say "Level 1 Completed". I'd appreciate any help. Here's the code. /** * Write a description of class endLevel1 here. * * @author (your name) * @version (a version number or a date) */ public class endLevel1 extends Actor { /** * Act - do whatever the endLevel1 wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { checkForIsTouchingPlayer1(); } public void checkForIsTouchingPlayer1() { if (isTouching(player1.class)) { addObject(new Win(), 100, 100); } } }
danpost danpost

2014/11/30

#
I do not understand. Is there an issue here? The code appears to be fine (presuming you left out the 'import greenfoot.*;' statement at the beginning).
qwerty1 qwerty1

2014/11/30

#
Yeah its there. I really don't see a reason why it shouldn't work.
danpost danpost

2014/11/30

#
Maybe the problem is in the Win class.
qwerty1 qwerty1

2014/11/30

#
What kind of problem? There's no code in the Win class because all that it has to do is be an image.
danpost danpost

2014/11/30

#
Oh, wait. You did not say anything about getting any error messages. Are you not getting a 'cannot find method addObject' error message?
qwerty1 qwerty1

2014/11/30

#
Yea sorry forgot to tell you that.
danpost danpost

2014/11/30

#
That would have been nice to know. It would have saved some time. There is no 'addObject' method in the Actor class. It is a World instance method and must be executed on a world object. You can use the Actor instance method 'getWorld' to get the world object that the actor is in:
getWorld().addObject(new Win(), 100, 100);
qwerty1 qwerty1

2014/11/30

#
Thanks, danpost! Sorry I didn't tell you about the error from the beginning. I have one more question. I can see the Win image, but it won't show up when I need it to because as you said the addObject method is a world instance method and cannot be used by Actors. However, the reason that I wrote the code was so that when the player1 class and the endLevel1 class touched, the Win class would appear. Would there be a way to make that happen?
danpost danpost

2014/11/30

#
Please read my last post again. I did not say that you cannot code it within an Actor subclass; I said it must be executed on a world object. That does not mean that is must be coded in a World subclass to execute.
You need to login to post a reply.