Search code examples
javapositionmouse-cursor

Keep mouse within Ellipse2D


I know how to keep my mouse (my g.draw(mouseX, mouseY) cursor) within a Ellipse2D / Shape…

@Override
public void mouseMoved(MouseEvent e) {
    int x = e.getX(), y = e.getY();
    if(shape.contains(x, y)) {
        mouseMoveX = e.getX();
        mouseMoveY = e.getY();
    }
}

…but this locks the movement entirely when the mouse leaves said shape (until it returns). IE it remains in the same position even though the actual cursor is moving around. I would like the mouse to be able to move around the Ellipse even though the actual cursor is out. Many of you may still be confused, sorry for that, if any more explanation is required I would be happy to oblige. Also, first question here so please let me know if I broke any rules! Thanks.

PS: Sorry for any late responses, currently on dialup internet :(


Solution

  • The simplest way to do this would be to use the java.awt.Robot class, which allows you to directly control the mouse and keyboard:

    import java.awt.Robot;
    
    ...
    
    Robot robot = new Robot(<your GraphicsDevice>);
    
    ...
    
    @Override
    public void mouseMoved(MouseEvent e) {
        int x = e.getX(), y = e.getY();
        if(shape.contains(x, y)) {
            mouseMoveX = e.getX();
            mouseMoveY = e.getY();
        }
        else {
            robot.mouseMove(mouseMoveX,mouseMoveY); // Assuming these are the previous coordinates.
        }
    }
    

    Edit: Okay, try this instead:

    @Override
    public void mouseMoved(MouseEvent e) {
        int x = e.getX(), y = e.getY();
        if (shape.contains(x, y)) {
            mouseMoveX = e.getX();
            mouseMoveY = e.getY();
        }
        else {
            // get angle of rotation
            double r = Math.atan2(y-shape.getCenterY(),x-shape.getCenterX());
            mouseMoveX = (int) (shape.getWidth()/2 * Math.cos(r) + shape.getCenterX());
            mouseMoveY = (int) (shape.getHeight()/2 * Math.sin(r) + shape.getCenterY());
        }
    }