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

2016/2/21

Accessing a classes method Through getOneObjectAtOffset

TheJohny TheJohny

2016/2/21

#
Hello everyone, I would like to ask if there is any way of accessing a certain class using the method getOneObjectAtOffset(). I have a scenario with blocks (that have certain health) and bouncy balls. Whenever the ball hits a block it bounces off of it (changes the velocity). But I would also like to substract one life of the block whenever that happens. Is there any proper way to do that ?
danpost danpost

2016/2/21

#
TheJohny wrote...
Hello everyone, I would like to ask if there is any way of accessing a certain class using the method getOneObjectAtOffset(). I have a scenario with blocks (that have certain health) and bouncy balls. Whenever the ball hits a block it bounces off of it (changes the velocity). But I would also like to substract one life of the block whenever that happens. Is there any proper way to do that ?
I think the only code you need to show is that which detects a block and has the velocity changed.
TheJohny TheJohny

2016/2/21

#
1
2
3
4
5
6
7
8
if(getOneObjectAtOffset(0,- imgHalf-1, Block.class) != null ||
        getOneObjectAtOffset(0, imgHalf+1, Block.class) != null){
            yVel *= -1;
        }
if(getOneObjectAtOffset(-imgHalf-1, 0, Block.class) != null ||
        getOneObjectAtOffset(imgHalf+1,0, Block.class) != null){
            xVel *= -1;
        }
I can post the entire scenario, if that would help
danpost danpost

2016/2/21

#
Okay, it is a little more complicated than I thought it might be because you are using dual compound conditions. To keep in line with what you already have, this would be more like what you would need for the first half:
1
2
3
4
5
6
7
8
9
10
Block blockUp = (Block) getOneObjectAtOffset(0, -imgHalf-1, Block.class);
Block blockDown = (Block) getOneObjectAtOffset(0, imgHalf+1, Block.class);
if (blockUp != null || blockDown != null){
    yVel *= -1;
    if (blockUp != null){
        blockUp.hit();
    }else{
        blockDown.hit();
    }
}
I used 'hit' for the method in the Block class to decrease the health of a block. You should have a 'public' method in the Block class to decrease its health and check for no health remaining (and, I presume, removing the block from the world at that point). That method is referred to as 'hit' in the code given above.
TheJohny TheJohny

2016/2/21

#
You are the boss! Works perfectly, thanks alot :) I wasn't aware that it is possible to convert an Actor into a Class type
danpost danpost

2016/2/21

#
TheJohny wrote...
You are the boss! Works perfectly, thanks alot :) I wasn't aware that it is possible to convert an Actor into a Class type
The bottom of this page of the java tutorials explains about explicit casting.
You need to login to post a reply.