Search code examples
javagraphics2d

move object on path (circle)


I need to move an object, in my case a String on a given Path. Actually the path could be half circle. As shown in the attached picture, the String should appear BEHIND another object, move along the path and disappear behind a second object (both Images(s)). I have no clue how to start...hope someone could help me. Thanks in advance.

enter image description here


Solution

  • Create a new Thread that will handle the logic for the text move. In its run() method you add a loop that will change the text position on each iteration. Also, after changing the text position, you will have to call repaint() on the component defining the paint() or paintComponent() that you have overwritten.

    After each iteration, the thread should sleep for a short time. Sleeping for 50ms means you will roughly get about 20 frames per second.

    Now for the math. Let's suppose that you know one point as being the center of the circle (somewhere below the middle point between the 2 images) and the starting point of the text. Having this, you can calculate the circle radius as being the distance between the 2 points:

    d = Math.sqrt((c.x - p.x) * (c.x - p.x) + (c.y - p.y) * (c.y - p.y))
    

    In order to keep the text moving on the circle, the above distance needs to be constant. So, what you can do is to increment the x by a constant value and calculate the new y for the text.

    d = Math.sqrt((c.x - p.x) * (c.x - p.x) + (c.y - p.y) * (c.y - p.y))
    

    In the above formula, you know the values d, c.x, c.y, p.x (you have just calculated and incremented it). You only need the value for p.y, which is:

    p.y = c.y - Math.sqrt(d * d - ((c.x - p.x) * (c.x - p.x))