Search code examples
javagreenfoot

Get object to follow mouse in Java/Greenfoot


I have just started using greenfoot for school and I would like to create a game like this one: http://www.scirra.com/arcade/action/455/squared but I am having trouble getting the actor/object to follow my mouse. Like the black square does in the mentioned game. I have tried this code so far but to no avail.

MouseInfo mouse = Greenfoot.getMouseInfo();
        setLocation(mouse.getX(), mouse.getY());
        if (mouse != null)
        {
        setLocation(mouse.getX(), mouse.getY());
        }

Solution

  • I found this while searching for an answer on Google and it showed how to get the object to follow your mouse. http://www.datraughber.com/prog1/greenfoot/unit3.pdf

    Original Code:

        MouseInfo mouse = Greenfoot.getMouseInfo();
        setLocation(mouse.getX(), mouse.getY());
    
        if (mouse != null)
        {
        setLocation(mouse.getX(), mouse.getY());
        }
    

    New Code

    if(Greenfoot.mouseMoved(null))
            {
                    MouseInfo mouse = Greenfoot.getMouseInfo();
                    setLocation(mouse.getX(),mouse.getY());
            }
    

    Thanks for trying to help Ajay Venugopal