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

2012/5/19

Help for mouse.

h123n h123n

2012/5/19

#
Hi! I have made complex things with get X get Y and get rotation yet I have no idea how to make an event so that when the mouse clicks on an object it does something. Can anyone help?
trash1000 trash1000

2012/5/19

#
if(Greenfoot.mouseClicked(this)) {
    //whatever the object should do now
}
h123n h123n

2012/5/19

#
Thanks!!! can someone tell me how to make it so that you can drag the item? here is my code in case you are need it.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class bear here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class bear extends Actor
{
    /**
     * Act - do whatever the bear wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if(Greenfoot.mouseClicked(this)) {
            move(4);
    }    
}
}
SPower SPower

2012/5/19

#
Do something like this:
if (Greenfoot.mouseClicked(this)) {
     MouseInfo info = Greenfoot.getMouseInfo();
     setLocation(info.getX(), info.getY());
}
This creates a new MouseInfo object, and you can ask questions to this about the mouse: including the location. Then, we set our location to the location of the mouse.
danpost danpost

2012/5/19

#
You need an instance boolean variable (or field) to track 'mouse pressed on me, and not yet released' or 'dragging'. Set it to 'true' if mouse pressed on this object. Set it to 'false' if the mouse is clicked (released) anywhere (use 'null' as parameter). Write an 'if' block to follow the mouse (SPower's code, but using 'if (dragging && Greenfoot.mouseMoved(null)) {' in line 1).
You need to login to post a reply.