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

2015/6/10

How do I call a public int variable from my World Class to Actor Class?

Heneong Heneong

2015/6/10

#
My world is SpaceBack, which has "public int NumberLasers = 0;" and I need to somehow use the same integer (NumberLasers) in my Actor Class named "Ship". Could someone explain that to me in the simplest means possible?
plant plant

2015/6/10

#
In your SpaceBack world you could add a constructer that returns the "NumberLasers" as shown below..
1
2
3
public int getNumberLasers(){
        return NumberLasers;
    }
In your "Ship" class you could call the method that you just made in the world by doing this..
1
2
3
4
5
6
private int placeholder = 0;
    public void act(){
        SpaceBack world = (SpaceBack)getWorld();
        world.getNumberLasers();
        placeholder = world.getNumberLasers();
    }
I created a integer to store the integer from the world into this new integer called "placeholder". Hope that helps!
Heneong Heneong

2015/6/10

#
Yes, it worked! Thanks plant!
Heneong Heneong

2015/6/10

#
Hi, I'm now stuck with another problem. The int NumberLasers, or "placeholder", was supposed to act as a counter, and once the counter reached 4, no more lasers could be shot. I've incremented placeholder++, but it doesn't seem to work. What is the problem here?
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
import greenfoot.*;
 
public class Ship extends Actor
{
    private int placeholder = 0;
    public void act()
    {
        // Add your action code here.
        SpaceBack world = (SpaceBack)getWorld();
        world.getNumberLasers();
        placeholder = world.getNumberLasers();
        if (Greenfoot.isKeyDown("up"))
        {   
            setLocation(getX(), getY()-3);
        }
        if (Greenfoot.isKeyDown("down"))
        {   
            setLocation(getX(), getY()+3);
        }
        if (Greenfoot.isKeyDown("f"))
        {   
            if(placeholder < 4)
            {
                LaserBeam Laser = new LaserBeam();
                getWorld().addObject(Laser, getX()+75, getY());
                placeholder++;
            }
        }
    }
}
danpost danpost

2015/6/10

#
Increasing the 'placeholder' field of your Ship object does not increase the 'NumberLasers' field in your SpaceBack object. Anyway, it is usually not a good idea to have two different fields hold the same information (one reason is because of the issue you are experiencing here). If each Ship object created is allowed to fire up to 4 lasers, then the field should be an instance field in the Ship class -- not in the world class. Also, as such, you would not have to acquire the value from the world.
You need to login to post a reply.