top of page

/**
 * CLASS: ShakeWorld
 *
 * DESCRIPTION: creates a world that shakes when prompted
 */


import greenfoot.*;

 

public class ShakeWorld extends DemoWorld
{
   
// class constants
    public static final int WIDE = 600; // world width (viewport)
    public static final int HIGH = 400; // world height (viewport)

    // instance fields
    Scroller scroller; // reference to Scroller object
    int strength;

​

    // creates a limited scrolling world
    public ShakeWorld()
    {
        super(WIDE, HIGH, 1, false);
// create an unbounded world
        // values needed to create the scroller object
        GreenfootImage image = new GreenfootImage("bg.png")); // the background img
        int wide = image.getWidth(); // the width of scrolling area
        int high = image.getHeight(); // the height of scrolling area
        scroller = new Scroller(this, image, wide, high); // create Scroller object
    }

​

    public void act()
    {
        scroll();
    }

​

    // performs shaking of world (random diminishing strength chaotic shakes)
    private void scroll()
    {
       
// check for shake
       
if (strength > 0 && --strength%4 == 0) // every four act cycles until rest
        {
            int dsx = 0, dsy = 0;
// scrolling offsets
            int distance = strength/4; // maximum offset
            // get random x and y-offsets up to +/- maximum
            dsx = distance-Greenfoot.getRandomNumber(distance*2+1);
            dsy = distance-Greenfoot.getRandomNumber(distance*2+1);
            // scroll negating previous scrolling

            dsx -= scroller.getScrolledX();

            dsy -= scroller.getScrolledY();
            scroller.scroll(dsx, dsy);
        }
    }
   
   
// called to initiate or re-strengthen shaking
    public void shake()
    {
        strength = 29;
    }
}


To shake only vertically:

 
// performs shaking of world (standard diminishing oscillating wave shake)
private void scroll()
{
   
// check for shake
    if (strength > 0 && --strength%4 == 0) // every four act cycles until rest
    {
        
// the '2*(..)-1' part in the next line alternates the sign
        int dsy = (strength/4)*(2*((strength/8)%4)-1)); // scrolling offset
        // scroll negating previous scrolling
        scroller.scroll(0, dsy-scroller.getScrolledY());
    }
}

SHAKING SCROLLING

bottom of page