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

2014/11/23

Lever to change movement speed

Favna Favna

2014/11/23

#
Hey all, Need some help with how I can program the following: What I want is that when my player moves over a lever object the movement speed of certain "bolt" objects gets edited from 5 to 1. The way my scenario currently looks is this: (disregard the sprites I used, no inspiration lol) I have tried many ways but all to no avail. My bolt class:
public class Bolt extends Actor
{
    public int boltspeed = 5;
    /**
     * Act - do whatever the Bolt wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move();
    }
    
    public void move()
    {
        //moves bolt from bottom-right to top-right
        if(getX() >= 75)
        {
            setLocation(getX() + boltspeed, getY());
        }

        //moves wallmaster from top-right to top-left
        //         Actor Bolt;
        if(getX() == 165)
        {
            World world = getWorld();
            world.removeObjects(getWorld().getObjects(Bolt.class));
            world.addObject(new Bolt(), 75, 375);
            world.addObject(new Bolt(), 75, 405);
            world.addObject(new Bolt(), 75, 435);
        }
    }
}
Lever is currently empty (except an empty Act method anyway). Same goes for Player for as far as this problem goes. (there are many other methods that deal with completely other things there)
danpost danpost

2014/11/23

#
Since the field 'boltspeed' is to reflect the speed of ALL your Bolt objects, you can make the field a 'static' one:
public static int boltspeed = 5;
Then, from anywhere in your project you can use something similar to the following to change the speed of all the bolts at once:
Bolt.boltspeed = 1;
Be sure to set the value of 'boltspeed' to its initial value in your initial world constructor or else any changes previous made to it will stay in effect (only re-compiling the project will reset a static field -- resetting the project does not re-compile the project). BTW. there is no need to remove and replace the bolts when they reach the right-hand limit. Just move them back to the left. The following can replace lines 23 through 30 of your Bolt class above:
if (getX() >= 165) setLocation(75, getY());
You probably do not need the condition on moving right at line 16. In other words, you can probably remove lines 16, 17 and 19 without any problems.
Favna Favna

2014/11/23

#
Works perfectly, thanks :)
You need to login to post a reply.