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

2012/10/12

Losing tokens when hitting an enemy

Kevin_Bacon Kevin_Bacon

2012/10/12

#
I'm making a scenario, and one of the requirements is losing collected items when colliding with an enemy. I know how to do this with variables, but I don't know how to give the player a visual indication of this happening. Like, let's say I hit the same enemy twice. After the second time, all tokens are lost, and all the ones lost go back into the world at random places. How would I do this?
Kevin_Bacon Kevin_Bacon

2012/10/15

#
bump
gusbus123 gusbus123

2012/10/15

#
int worldX = Greenfoot.getRandomNumber(getWorld().getWidth()));
int worldY = Greenfoot.getRandomNumber(getWorld().getHeight()));

for(int i=0; i<TotalAmountOfTokensPlayerHas; i++) getWorld().addObject(new Token(), worldX, worldY);
try this, the getWorld().getWidth and getHeight part might need to be changed, i didnt check with the codes.
Kevin_Bacon Kevin_Bacon

2012/10/16

#
What object would this code go into? Would it be under the act method for something?
danpost danpost

2012/10/16

#
The code given by gusbus123 will take the number of tokens the player has and put that many in one random place in the world; that is, they will all go the the same random place and appear to be only one token added (though, there may be many; one on top of another). To place the tokens in different locations, use the following code. BTW, both gusbus123 and I are guessing you have a variable in the player class to track the number of tokens the player currently has; but are not sure what you might have named it.
for (int i = 0; i < playerTokenCount; i++)
{
    int worldX = Greenfoot.getRandomNumber(getWorld().getWidth());
    int worldY = Greenfoot.getRandomNumber(getWorld().getHeight());
    getWorld().addObject(new Token(), worldX, worldY);
}
playerTokenCount = 0;
This code will go in the player's class, probably in the 'hitEnemy' method (or whatever you might have called it). You should add an instance Enemy variable (or field) to the player class, maybe called 'lastEnemyHit' (initially set to 'null'), and put the code above in an 'if' block asking 'if (lastEnemyHit == enemy)' (where 'enemy' is the current one). After the 'if' block, use 'lastEnemyHit = enemy;' to save the last enemy hit. That is the jist of what you need to do; but, since I do not know the name of your classes, you will have to adjust the code accordingly. Also, I did not show code on how to get anything assigned to the variable 'enemy'.
gusbus123 gusbus123

2012/10/16

#
oops, fail by me with the placement of the int's. lol
Kevin_Bacon Kevin_Bacon

2012/10/19

#
Thanks, it works. I made lastEnemyHit an int variable that increases as Hero makes contact with an enemy. When it hits a certain value, it plays the code. The whole thing is an if-statement.
You need to login to post a reply.