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

2017/5/26

Selecting units via a box

LichKing LichKing

2017/5/26

#
Hello all, I have a small-scale RTS I am writing and I cannot figure out how to select all units within an area. In most RTS, you click the mouse and then drag and everything inside gets selected. I cannot figure out how to do that. Can you help?
danpost danpost

2017/5/26

#
In my Conway''s Game of Life scenario, I implemented something similar to save an area of the grid. I had these parts: (the following maybe would be in your World subclass)
private Selector selector;
private boolean dragging;

public void act()
{
    if (!dragging && Greenfoot.mousePressed(this))
    {
        dragging = true;
    }
    if (dragging && Greenfoot.mouseDragged(this))
    {
        MouseInfo mi = Greenfoot.getMouseInfo();
        if (selector == null)
        {
            selector = new Selector(mi.getX(), mi.getY());                
            getWorld().addObject(selector, mi.getX(), mi.getY());
        }
        selector.resize(mi.getX(), mi.getY());
    }
    if (selector != null && Greenfoot.mouseDragEnded(this))
    {
        dragging = false;
        java.util.List objs = selector.getSelection();
        selector = null;
         // work with list of objects returned by 'selector.getSelection' here
    }
}
with the basics of the Selector class being:
public class Selector extends Actor
{
    int baseX = 0, baseY = 0;
    int across = 0, down = 0;

    public Selector(int startX, int startY)
    {
        baseX = startX;
        baseY = startY;
        updateImage();
    }
    
    public void resize(int newX, int newY)
    {
        across = newX-startX;
        down = newY-startY;
        updateImage();
        setLocation(startX+across/2, startY+down/2;
    }
    
    private void updateImage()
    {
        GreenfootImage img = new GreenfootImage((int)Math.abs(across)+1, (int)Math.abs(down)+1);
        mg.setColor(new Color(255, 96, 96, 96));
        img.fill();
        img.setColor(Color.red);
        img.drawRect(0, 0, img.getWidth()-1, img.getHeight()-1);
        setImage(img);
    }
 
    
    public java.util.List getSelection()
    {
        java.util.List actors = getIntersectingObjects(Actor.class);
        getWorld().removeObject(this);
        return actors;
    }
}
I had to simplify and modify the code to make it more generic in nature (to make it not so specific to the scenario the code originated from), so I hope I got it close without testing it.
You need to login to post a reply.