Search code examples
javaeclipseeventsmouseawtrobot

Java impassable region


I have a mouse event handler and under mouseMoved I have this:

public void mouseMoved(MouseEvent e)
{
  if((e.getX()>=0 && e.getX()<=100) && (e.getY()>=0 && e.getY()<=100))
  {
    robot.mouseMove(mainOutput.getX()+200,mainOutput.getY()+200);
  }
}

What this does is that if the user tries to move towards the first 100x100 pixels of the frame, the pointer will translated. What I want to do however is recreate an "impassable wall".

Basically when the user attempts to go in the region it cannot pass the end points of the region. What I want to know is how would I go about doing this?


Solution

  • Unfortunately, this is a bit more difficult than it seems. Let me first illustrate the problems with a simple move-to-outside-of-boundary approach.

    enter image description here

    As you can see, in this case the boundary approach will detect the mouse inside the boundary, and move it to the blue point in the corner. Let me emphasize this, it detects the location of the mouse. What we want is to capture the movement of the cursor, and have it end at the red point. There are also other problems with this method that may not be immediately apparent.

    So how do we capture the movement of the mouse? We need to capture the mouse displacement (black arrow) as a vector by keeping track of the previous location as well. I assume you can do this. So how do we calculate the new location? Well, we can perform line intersection of the displacement vector with the lines that make up the edges of the box. As you're only dealing with horizontal and vertical lines, it is greatly simplified and can be done with just a bit of thinking. If you're lazy, copy a generalized line intersection algorithm.

    You may think that this approach is too rigorous, but it is the most robust way. I can already think of two additional issues with the simpler approach. Also, you're actually doing 2D hitbox detection. This is quite a useful thing to know.