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

2014/1/26

Adding score in another class

Tupac Tupac

2014/1/26

#
Hey, I have a problem. Greenfoot videos on YouTube only display how to add score in the player class, but my player class shoots a cannonball, and the cannonball hits the object. When the cannonball hits the 'ship', I have to add the score by 1. So how do I do this?
Tupac Tupac

2014/1/26

#
Code in my player ship that fires the cannonball:
private void Fire()
    {
        Cannonball cannonball = new Cannonball();
        getWorld().addObject(cannonball, getX(), getY());
        cannonball.setRotation(getRotation());
        cannonball.move(25.0); 
        ((Counter) getWorld().getObjects(Counter.class).get(0)).add(1);
    }
But I want it to count when the cannonball hits the ship. So this is the code I have in my cannonball class:
public void CollideWithBoat() 
    {
        Actor boot;
        boot = getOneObjectAtOffset(0, 0, Boot.class);
        Actor boot2;
        boot2 = getOneObjectAtOffset(0, 0, Boot2.class);
        if (boot !=null)
        {
            World world;
            world = getWorld();
            world.removeObject(boot);
            if (boot !=null)
            {
                world = getWorld();
                world.removeObject(this);
                //((Counter) getWorld().getObjects(Counter.class).get(0)).add(1);
            }
        }        
        if (boot2 !=null)
        {
            World world;
            world = getWorld();
            world.removeObject(boot2);
            if (boot2 !=null)
            {
                world = getWorld();
                world.removeObject(this);
                //((Counter) getWorld().getObjects(Counter.class).get(0)).add(1);
            }
        }
    }
Tupac Tupac

2014/1/26

#
I also want to be able to get my 'highscore' to the next level. So how do I save the score for the next level as well?
danpost danpost

2014/1/26

#
Change lines 16 and 28 to:
((Counter)world.getObjects(Counter.class).get(0)).add(1);
Using 'getWorld' after 'this' has been 'removeObject'ed from the world will return a 'null' value' -- and no method can be executed (like 'getObjects') on an object that is not there (a 'null' object).
You need to login to post a reply.