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

2012/10/22

How to drag a world?

roronoa roronoa

2012/10/22

#
How can I drag a world?
davmac davmac

2012/10/22

#
what do you mean?
roronoa roronoa

2012/10/22

#
I press the mouse button on a random point on the world and then move it with the mouse still pressed that the image, which is to big for the screen moves together with the mouse. Just like for example google maps. Catch and drag scrolling.
erdelf erdelf

2012/10/22

#
so you mean, drag an image?
roronoa roronoa

2012/10/22

#
I mean to drag the image of the world.
Upupzealot Upupzealot

2012/10/22

#
Just use a actor with big image, and think he is the "world" When dragging, update the locations of the "world" and all things "in it" with your mouse.
Gevater_Tod4711 Gevater_Tod4711

2012/10/22

#
do you want this to hapen if the run button is pressed or if it's not pressed? if you want it when the button isn't pressed Upupzealot's way will work but if you want it to hapen while the szenario is executing it would be a bit tricky.
danpost danpost

2012/10/23

#
I came up with this code to drag an oversized image on the world background.
import greenfoot.*;

public class Pad extends World
{
    GreenfootImage image = new GreenfootImage("fractal.png"); // the oversized image
    int imgX, imgY; // holds current image offsets
    int prsX, prsY; // holds where mouse button first pressed
    boolean dragging; // flags dragging state
    
    public Pad()
    { 
        super(400, 400, 1);
        setBackground(image);
    }
    
    public void act()
    {
        if (!dragging && Greenfoot.mousePressed(null))
        {
            MouseInfo mi = Greenfoot.getMouseInfo();
            prsX = mi.getX();
            prsY = mi.getY();
            dragging = true;
        }
        if (dragging && Greenfoot.mouseDragged(null))
        {
            MouseInfo mi = Greenfoot.getMouseInfo();
            updateBackground(imgX - (prsX - mi.getX()), imgY - (prsY - mi.getY()));
        }
        if (dragging && Greenfoot.mouseDragEnded(null))
        {
            MouseInfo mi = Greenfoot.getMouseInfo();
            boolean bgChanged = updateBackground(imgX - (prsX - mi.getX()), imgY - (prsY - mi.getY()));
            if (bgChanged)
            {
                imgX -= prsX - mi.getX();
                imgY -= prsY - mi.getY();
            }
            dragging = false;
        }
    }

    public boolean updateBackground(int x, int y)
    {
        if (x > 0 || x < getWidth() - image.getWidth() + 1 || y > 0 || y < getHeight() - image.getHeight() + 1)
        {
            updateBackground(imgX, imgY);
            return false;
        }
        GreenfootImage bg = new GreenfootImage(getWidth(), getHeight());
        bg.drawImage(image, x, y);
        setBackground(bg);
        return true;
    }
}
You need to login to post a reply.