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

2015/3/30

How to spawn an object at xy location on mousehover?

YosuaZakaria YosuaZakaria

2015/3/30

#
So I am making a solar system animation, I want that when user hover their mouse over a planet at the xy location (right side of the world in my case) an object in form of image with all the details of the planet spawns, and when mousehover return null, then image will be removed. P.S: I know I can achieve it with object transparency but it's not efficient, eating memory, so anyone can help? P.S.S: I also use a code posted by danpost on this game (credit to danpost), i understand that the setLocation determine which xy location that is the center of the world, but so far it spawn my object on top side of the world (I also understand that radius determine how far object will spawn from center, with plus numbers spawn it at top side, negative bottom side), Anyone know if it's possible to spawn the object on left / right / whatever location i determine instead while keeping the circular pattern?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class sun extends Actor
{
    int rotational_speed = 1;
    int radius = 400;
 
    public void act()
    {
        //setLocation((getWorld().getWidth()/2), (getWorld().getHeight()/2));
        setLocation((960), (540));
        turn(rotational_speed-90);
        move(radius);
        turn(90);
    }
}
danpost danpost

2015/3/30

#
When creating the object, do something like this:
1
2
3
4
sun sunny = new sun();
addObject(sunny, 0, 0);
sunny.setRotation(90); // change as needed to determine spawn location
sunny.act(); // sets initial location
danpost danpost

2015/3/30

#
For the image, you will need a boolean field to track the last mouse hover state determined:
1
2
3
4
5
6
7
8
9
10
// instance field
private boolean mouseOn;
 
// in act method or method it calls
if (mouseOn != Greenfoot.mouseMoved(this))
{
    mouseOn = ! mouseOn;
    if (mouseOn) getWorld().addObject(...);
    else getWorld().removeObjects(getWorld().getObjects(...));
}
If you store an actor with the image of the detailed planet in a field in the class, then you can not only add, but remove, the object itself and not have to create it each time (to reduce any lag).
YosuaZakaria YosuaZakaria

2015/3/30

#
It works, thanks a lot danpost :) o7
You need to login to post a reply.