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

2014/1/13

Limiting & Reloading Ammo?

DSP512 DSP512

2014/1/13

#
Hi, I've a question: I want to limit the munition, so the player can only shoot a limited number of times and the remaining munition is shown by a counter. I already archieved the ammo limitation with this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Ship extends Actor {
public int ammo;
public Ship
{
ammo=15;
}
private boolean spaceDown;
public void shoot(){
if(!spaceDown && Greenfoot.isKeyDown("space"))
{
if(Munition()==true)
{
spaceDown=true;
getWorld().addObject(new Missile(), getX(), getY());
ammo--;
}
}
if(spaceDown && !Greenfoot.isKeyDown("space"))
{
spaceDown=false;
}
}
public boolean Munition(){
 if(ammo>0){
return true;
}
else{
return false;
}
}
}
How can I connect the shooting method with the AmmoCounter to show how many bullets are left. I already tried to archieve this like this Tutorial: How to access one object from another?, but it was not possible to count backwards fro e.g. 15 to 0 because I was only getting compiling errors. Another question is, how can I extend the number of available bullets by collecting additional ammo? For the collection I used this code:
1
2
3
4
5
6
public void collectAmmo(){
Actor ammo = getOneObjectAtOffset(0,0,Ammo.class);
if(ammo !=null){
getWorld().removeObject(ammo);
}
}
How can I reload the ammo?
danpost danpost

2014/1/13

#
You already have a field for the amount of ammo the ship has. All you really need is a Actor object to display that amount (a Counter object is just a glorified Text object that contains the int field for the amount and a String field for the caption with methods to change them and update the display). Actually, all you need is an Actor object whose image is set the GreenfootImage of the String value of "Ammo: "+ammo Refer to the GreenfootImage class documentation for the constructor that uses a String to create images out of. Just by setting/re-setting the image of the actor each time there is a change in the amount of ammo, you have, in essence, a displayed counter. To reload ammo, next to line 4 (either side), use 'ammo += addAmount;', where addAmount is the amount of ammo you want to add. Then follow it with a statement that updates the displayed amount of ammo left. This should also be done in the 'shoot' method after 'ammo--;'.
You need to login to post a reply.