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

2015/4/23

Making Objects Move Relative to Their Original Locations

jackyyang09 jackyyang09

2015/4/23

#
I'm trying to create a slider window for my program and I want be able to let it move around when dragged. The problem is that since the slider is an interactive object separate to the window itself, the only way I know of to make the slider follow the window is to use the setlocation method with the parameters of the window's x and y coordinates. What I want to happen is to not only have the slider follow the window but have the slider maintain it's current position relative to the window whilst following the window when being dragged by the mouse. What's happening now is that since I'm using:
1
slider.setLocation(getX(), getY() + 35);
to move my slider alongside the window, the slider will re-affix itself to the the x-coordinate of the window no matter what position it was at previously. Is there any sort of code/formula that will allow me to keep the slider in it's same position relative to the window while I move it around?
davmac davmac

2015/4/23

#
Before the window moves, calculate the relative position of the slider to the window and store it in variables (relX and relY). Probably something like:
1
2
int relX = slider.getX() - getX();
int relY = slider.getY() - getY();
Then after the window moves, move the slider to the same relative position:
1
slider.setLocation(getX() + relX, getY() + relY);
danpost danpost

2015/4/23

#
If the slider is not to move at all, then you could add the following to the Slider class to prevent any movement:
1
2
public void move(int amount) {}
public void setLocation(int x, int y) {}
This will hide the implementation of those methods provided by the Actor class for the Slider objects. That is not to say that you can no longer use those implementations at all. It is still possible to access the Actor class methods from within the class by prefixing the calls with 'super.'.
You need to login to post a reply.