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

2019/2/4

Access an actor's variables in another actor

Notted Notted

2019/2/4

#
I want to access a var named numOfBombs from the bucket actor. The reason for this is to use it in my bombSpawner actor for the speed up/slow down that he receives when the player gets a number of bombs (say 25) or when the player has less than said number. Here is my (non-functional) sublimation of what it would look like in code:
if (numOfBombs == 25)
        {
            bomberSpeed = bomberSpeed + 1;
        }
        if (numOfBombs == 50)
        {
            bomberSpeed = bomberSpeed + 2;
        }
        if (numOfBombs == 75)
        {
            bomberSpeed = bomberSpeed + 3;
        }
         if (numOfBombs == 100)
        {
            bomberSpeed = bomberSpeed + 4;
        }
Is this a good way to do it? Would it be better with else if? I also have this:
 private bucket playerBucket;
    public bucket getABucket()
    {
        return playerBucket;
    }
    private bombSpawner theBomber;
    public bombSpawner getABomber()
    {
        return theBomber;
    }
inside the myWorld class. Could this help?
danpost danpost

2019/2/4

#
Notted wrote...
<< Code Omitted >> Is this a good way to do it? Would it be better with else if?
What would be better is with no else AND no if either. It is simple:
bomberSpeed = 4+(numOfBombs/25);
Get the value of numOfBombs with:
int numOfBombs = ((MyWorld)getWorld()).getABucket().getNumOfBombs();
(assuming you have a getNumOfBombs method in the bucket class).
Notted Notted

2019/2/5

#
I found a problem with my movingBomber() code. It seems that whenever the gotoX is equal to the actors x (from getX), he hits an invisible wall, and then spasms insanely, making him stuck.
int numOfBombsRef = ((MyWorld)getWorld()).getABucket().getNumOfBombs();
        move(bomberSpeed);
        bomberSpeed = 4+(numOfBombsRef/25);
        if ((getX()-gotoX >= 0 && bomberSpeed > 0) || (getX()-gotoX <= 0 && bomberSpeed < 0))
        {
            bomberSpeed = -bomberSpeed;
            int width = getWorld().getWidth();
            gotoX = width/2+(50+Greenfoot.getRandomNumber(width/2-80))*bomberSpeed/4;
        }
    }
The gotoX = 220 (100 less than of the width of the game world).
danpost danpost

2019/2/5

#
Notted wrote...
I found a problem with my movingBomber() code. It seems that whenever the gotoX is equal to the actors x (from getX), he hits an invisible wall, and then spasms insanely, making him stuck. << Code Omitted >> The gotoX = 220 (100 less than of the width of the game world).
Try changing line 3 to this:
bomberSpeed = (int)Math.signum(bomberSpeed)*(4+numOfBombsRef/25);
You need to login to post a reply.