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

2015/3/31

Help- removing objects

Leenza Leenza

2015/3/31

#
In my game I have things that you collect to increase your speed. However, I only want them on the screen for the first 10 seconds of the level or something like that. After that I don't want them to be on the screen anymore (like they just disappear, the hero doesn't collide with them or anything), and therefore it is impossible to collect these things. I tried this code:
if (GameWorld1.PowerUpTimer.millisElapsed() > 10000)
        {
            GameWorld1.removeObject(PowerUp);

        }
But it won't compile. What am I doing wrong?
danpost danpost

2015/3/31

#
It would be much easier to have the PowerUp objects remove themselves after so many act cycles. Using system time is not as good as counting act cycles because if the 'Pause' button is pressed or the system momentarily lags, then game-time is lost. Act cycles are much easier to count and deal with, also. I believe that the problem with your code above is the use of class names where you need to refer to objects of those classes. For example, the 'removeObject' method requires an Actor object that is to be removed. 'PowerUp' is not an object, it is a class name. It is difficult to determine whether 'PowerrUpTimer' is another class name or a field name; but because it starts with an uppercase letter, it would normally be perceived as being another class name. However, with the way it is used (following 'GameWorld1', which would be almost definitely perceived as a class name), it would seem that 'PowerUpTimer' is actually a field name that holds an object. I think I would like to see how the 'PowerUpTImer' field is declared in the GameWorld1 class; and if it does indeed hold an Object, I would also like to see the code of the class for the type of object the field holds.
Super_Hippo Super_Hippo

2015/3/31

#
As danpost suggested, you can simply use something like this in the PowerUp class instead:
private int time = 0;

public void act()
{
    time++;
    if (time>550) getWorld().removeObject(this);
}
Leenza Leenza

2015/3/31

#
Thank you so much @danpost and @Super_Hippo. That was very helpful and I got it working.
Leenza Leenza

2015/4/1

#
Actually I need help again. My game is a multi level game and when I do the code suggested above it wont add the powerups to the next level even though I have a code in the next world class to put them there
Super_Hippo Super_Hippo

2015/4/1

#
Show the code which should add the power ups to the next level.
Leenza Leenza

2015/4/1

#
For (int x=0; x < numPowerUps; x++)
{
XPos = Greenfoot.getRandomNumber(getWidth());
YPos = Greenfoot.getRandomNumber(getHeight());
Addobject(new PowerUp(), xPos, yPos);
Leenza Leenza

2015/4/1

#
And that works without having the power up code (sorry if my formatting is off I'm doing this on my phone)
You need to login to post a reply.