I want to move a Graphics object towards the cursor when the user clicks a mousebutton, but I’ve got no idea how…
I have the position of the cursor and the Graphic object, but no clue on how i would change its X and Y to make “smooth” movement from the start location to the new point (where the user clicked)…
General approach:
Have a model backing your graphics, and store the coordinate of each item in the model on the model.
It’s important that you update x and y in the same thread, not independent threads. That sounds like a cool idea, but it fails because the thread scheduler will sometimes lag one thread and you can get 2 or 3 updates on one dimension without a corresponding update in the other, which will cause the object to move in a line that is not smooth. In most cases you should do all your updates to the model (for this and any other motion) in the same thread.
Note that your x & y in your model probably need to be float or double since you don’t want to loose fractions of a pixel, especially if the motion is intended to be slow. Expressing the equation in terms of distance remaining avoids having to calculate the angle of the trajectory and using sine/cosine functions to perform the update. However, in some cases you may find it easier to calculate that angle and use sine/cosine instead, if you want a complex motion that isn’t easily transformed to be expressed in terms of distance remaining. Do what makes your code clear, optimize later if needed.
24 updates per second is the standard frame rate for movie cameras and that number is a minimum that relates to flicker fusion of the human eye, if you update slower than that people will see the motion as jerky. For maximum smoothness you would want over 60 times a second, but that’s probably only necessary for video games and creates a much bigger performance cost. Pick the minimum update rate that you find visually satisfactory.
It’s also a good idea to have a flag on the update thread that turns it on and off when there’s something to update so it isn’t requesting repaint for no reason when there’s nothing to animate. Be sure that the flag is marked with the volatile keyword since it will be updated by other threads. If you have multiple animations going on at one time, you might turn the thread on and off based on presence of animation objects in a list (removing them when they are complete)