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

2016/7/31

problem with getOneIntersectingObject

bernhard bernhard

2016/7/31

#
Hello, I want one of my actors to pick up a powerup when touching it and then perform its effect. There are different powerups however it's all the same class. There is an integer that specifies which kind of powerup they are. So for the actor that picks them up to know the powerup's type, I tried this:
public void pickUpPowerup()
    {
        Actor powerup = getOneIntersectingObject( Powerup.class );
        if( powerup != null )
        {
            switch( powerup.getType() )
            {
                 ....
The error says, the method getType() was not found but the class Powerup contains just that method. I think the problem is, that the getOneIntersectingObject-method returns an actor (and not a Powerup?) but I can't figure out how to fix this. The only way I know is to make each powerup an own class but I would like to avoid that. Thanks in advance for your suggestions.
danpost danpost

2016/7/31

#
bernhard wrote...
I think the problem is, that the getOneIntersectingObject-method returns an actor (and not a Powerup?) but I can't figure out how to fix this.
That is close to the problem, but without the proper understanding of why. Line 3 creates a variable reference to an Actor object of NO particular type (although the method specifically looks for Powerup objects). In order for you to access the 'getType' method on that reference, you need to inform the compiler that the reference refers to a Powerup type object. There are a couple of places you can adjust the code to do this. You can have the reference refer specifically to a Powerup object by changing line 3 to:
Powerup powerup = (Powerup)getOneIntersectingObject(Powerup.class);
or you can typecast the reference when calling the 'getType' method by changing line 6 to:
switch (((Powerup)powerup).getType())
bernhard bernhard

2016/7/31

#
Thank you for explaining, works just fine now. :)
You need to login to post a reply.