Search code examples
javashapesdragslick2d

Java Slick2d - how to keep a shape allways inside a window?


I'm moving a circle across the window by dragging it with the mouse. I'm supposed to make it always inside the window.

So by the default, when you drag the circle in a way that your mouse exits the frame, half of the circle will disappear (because it exits the frame), and half of it won't. I need to make it visible whole all the time, even if your cursor exits the frame. Here's the code:

if(draggingcircle)
{
  g.drawString("Dragging circle = " + draggingcircle, 50, 110);
  circle.setCenterX( gc.getInput().getMouseX() );
  circle.setCenterY( gc.getInput().getMouseY() );
}

Solution

  • whatever the circle is contained in, lets call id , you can keep it in the container with simple math if you know the radius or the diameter (i forget which)

    so

    if(draggingcircle)
    {
      g.drawString("Dragging circle = " + draggingcircle, 50, 110);
      circle.setCenterX( gc.getInput().getMouseX() );
      circle.setCenterY( gc.getInput().getMouseY() );
    }
    

    becomes

    var width = $('#container').width();
    var height = $('#container').height();
    var radius = 2;
    
    if(draggingcircle)
    {
      g.drawString("Dragging circle = " + draggingcircle, 50, 110);
      if (gc.getInput().getMouseX() > radius && gc.getInput().getMouseX() < width - radius)
      {
        circle.setCenterX( gc.getInput().getMouseX() );
      }
      if (gc.getInput().getMouseY() > radius && gc.getInput().getMouseY() < height - radius)
      {
        circle.setCenterY( gc.getInput().getMouseY() );
      }
    }
    

    Sorry for my poor syntax, I am not familiar with Slick2d, but something along these lines should work.